Reputation: 67
I have two json objects. Both may have common keys, Some present only in first object, while some present only in second. When I come these two objects the structure of objects should not change. Only a new level of keys will be added such as the specifying for which object that value belongs to. Even the structure of json objects represent a hierarchy whose levels are not fixed.
a = {"parent1" : { "childa1" : { "grandchilda11" : { "data": values},
"grandchilda12" :{"data" : values }
}
"data" : values
}
{ "childa2" : { "grandchilda21" : { "data": values},
"grandchilda22" :{"data" : values }
}
"data" : values
}
}
b = { "parent1" : { "childa1" : { "grandchilda11" : { "data": values},
"grandchilda12" :{"data" : values }
}
"data" : values
}
{ "childa2" : { "grandchilda21" : { "data": values},
"grandchilda22" :{"data" : values }
}
"data" : values
},
"parent2" : { "childb1" : { "grandchildb11" : { "data": values},
"grandchildb12" :{"data" : values }
}
"data" : values
}
{ "childb2" : { "grandchildb21" : { "data": values}
}
"data" : values
}
}
The resultant should combine this type of json string . The data level here contains directly values while in the resultant it should be like which object it belongs acting as key and then values .
"data" : { "a" : values , "b":values}
Upvotes: 0
Views: 4092
Reputation: 2061
Try this:
def merge(obj1, obj2):
for key in obj2:
obj1[key] = obj2[key]
return obj1
Upvotes: 1
Reputation: 2058
I think this may be what you're looking for.
If you have data dictionaries a
and b
you can call the below function using merge(a, b)
to merge the two like you've said. It does rely on the assumption that both dictionaries have the same structure to them.
def merge(a, b):
if type(a) is str:
return { 'a': a, 'b': b }
else:
for key in a:
a[key] = merge(a[key], b[key])
return a
Upvotes: 1