I have a json file like this:
{
"parent1": {
"child1": "bob"
},
"parent1": {
"child2": "tom"
},
"parent2": {
"child1": "jon"
}
}
I want to merge the values present under duplicate toplevel keys. So the expected output should be:
{
"parent1": {
"child1": "bob",
"child2": "tom"
},
"parent2": {
"child1": "jon"
}
}
Currently I am using the following code to check duplicate keys:
import json
def check_duplicates(pairs):
d = {}
for key, val in pairs:
if key in d:
raise ValueError(f"Duplicate key(s) found: {key}")
else:
d[key] = val
return d
filename = "test.json"
with open(filename, "r") as f:
try:
data = json.load(f, object_pairs_hook=check_duplicates)
except ValueError as err:
print(f"{filename}: Failed to decode: {err}")
Any idea how I can merge them?
New contributor
sjko5 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.