Reputation: 714
Here is the example:
I have this jsonA
{ "a":"1", "b":"2", "c":{"a":"1", "b":"2"} }
and this jsonB
{ "b":"2new", "c":{"a":"1new"} }
I want update the first jsonA with the new value in jsonB and, at the end, have this result:
{ "a":"1", "b":"2new", "c":{"a":"1new", "b":"2"} }
manually i could to set every value, like:
jsonA.b = jsonB.b;
jsonA.c.a = jsonB.c.a;
There is a way to do it automatically without check every valule with a forEach?
Upvotes: 0
Views: 212
Reputation: 393789
Because you hadn't specified the language tag, I went ahead and implemented it in c++.
Here's the main program:
int main()
{
auto jsonA = JSON::parse("{ \"a\":\"1\", \"b\":\"2\", \"c\":{\"a\":\"1\", \"b\":\"2\"} }");
auto jsonB = JSON::parse("{ \"b\":42, \"c\":{\"a\":\"1new\"}, \"q\":[3.14,null] }");
if (boost::apply_visitor(make_love(), jsonA, jsonB))
std::cout << "Merged: " << jsonA;
else
std::cerr << "Couldn't merge '" << jsonA << "' with '" << jsonB << "'\n";
}
Output:
Merged: {"a":"1","b":42,"c":{"a":"1new","b":"2"},"q":[3.14,null]}
Of course, this just begs the question of how make_love
is implemented:
struct make_love : boost::static_visitor<bool>
{
bool operator()(Object& a, Object const& b) const {
for(auto el: b.values)
recurse(a[el.first], el.second);
return true;
}
template<typename T, typename U> bool operator()(T& a, U const& b) const
{ return false; }
private:
void recurse(Value& a, Value const& b) const {
if (!boost::apply_visitor(*this, a, b))
a = b;
}
};
Full code in context (JSON.hpp/JSON.cpp): https://github.com/sehe/spirit-v2-json/blob/q17711850/test.cpp
Upvotes: 6
Reputation: 12681
I just wrote this:
jsonA = { "a":"1", "b":"2", "c":{"a":"1", "b":"2"} }
jsonB = { "b":"2new", "c":{"a":"1new"} }
for (var j in jsonA) {
if(jsonB.hasOwnProperty(j)) {
if (typeof jsonA[j] === 'object') {
for (var i in jsonA[j]) {
if(jsonB[j].hasOwnProperty(i)) {
jsonA[j][i] = jsonB[j][i];
}
}
} else {
jsonA[j] = jsonB[j];
}
}
}
Check it out here: http://jsfiddle.net/YtgQS/
Upvotes: 1