I'm trying to merge two JSON files into a single JSON using python.
File1:
{
"key1": "protocol1",
"key2": [
{
"name": "user.name",
"value": "[email protected]"
},
{
"name": "user.shortname",
"value": "user"
},
{
"name": "proxyuser.hosts",
"value": "*"
},
{
"name": "kb.groups",
"value": "hadoop,users,localusers"
},
{
"name": "proxy.groups",
"value": "group1, group2, group3"
},
{
"name": "internal.user.groups",
"value": "group1, group2"
}
]
}
File2:
{
"key1": "protocol1",
"key2": [
{
"name": "user.name",
"value": "[email protected]"
},
{
"name": "user.shortname",
"value": "user"
},
{
"name": "proxyuser.hosts",
"value": "*"
},
{
"name": "kb.groups",
"value": ""
},
{
"name": "proxy.groups",
"value": "group3, group4, group5"
},
{
"name": "internal.groups",
"value": "none"
}
]
}
Final expected result:
{
"key1": "protocol1",
"key2": [
{
"name": "user.name",
"value": "[email protected], [email protected]"
},
{
"name": "user.shortname",
"value": "user"
},
{
"name": "proxyuser.hosts",
"value": "*"
},
{
"name": "kb.groups",
"value": "hadoop,users,localusers"
},
{
"name": "proxy.groups",
"value": "group1, group2, group3, group4, group5"
},
{
"name": "internal.user.groups",
"value": "group1, group2"
},
{
"name": "internal.groups",
"value": "none"
}
]
}
I need to merge based on below rules:
If the 'name' key within the
list(key2)match in both the files then concatenate the values.e.g.
File1:
"key2": [{"name" : "firstname", "value" : "bob"}]File2:
"key2": [{"name" : "firstname", "value" : "charlie"}]Final output:
"key2": [{"name" : "firstname", "value" : "bob, charlie"}]
Some considerations while appending the values:
If both files contain duplicate value(s) in 'value', final result should only be the union of the values.
If any of 'value' contains ' * ', then final value should be ' * '.
- If 'name' key in 2nd JSON file is not present in 1st file, add it to first file.
I've written a python script to load the two JSON files and merge them but it seems to just concatenate everything into the first JSON file.
def merge(a, b):
"merges b into a"
for key in b:
if key in a:# if key is in both a and b
if key == "key1":
pass
elif key == "key2":
for d1, d2 in zip(a[key], b[key]):
for key, value in d1.items():
if value != d2[key]:
a.append({"name": d2[key], "value": d2["value"]})
else:
a[key] = a[key]+ b[key]
else: # if the key is not in dict a , add it to dict a
a.update({key:b[key]})
return a
Can someone point out how I can compare the value for the "name" section with the list for key2 in both the files and concatenate the values in "value"?