Reputation: 1019
I am looking to merge two JSON strings into one in Python. string1 has identical Keys as string2, but string2 has several values in a list, like the example below:
string1:
{'Target': 'DEV1', 'Supplier': '0', 'Message': 'A', 'Name': 'Supp1'}
string2:
{'Target': ['DEV2', 'DEV3'], 'Supplier': ['1', '2'], 'Message': ['B', 'C'], 'Name': ['Supp2', 'Supp3']}
Hopeful Merged Output string3:
{'Target': ['DEV1', 'DEV2', 'DEV3'], 'Supplier': ['0', '1', '2'], 'Message': ['A', 'B', 'C'], 'Name': ['Supp1', 'Supp2', 'Supp3']}
I'm not too familiar with JSON, but here's my current position:
import json
str1 = json.loads(string1)
str2 = json.loads(string2)
string3 = {key, val for (key, val) in (str1.items() and str2.items())
The last line I found in Stackoverflow for merging JSON strings, but I am struggling with the list appending for each value.
Any help would be greatly appreciated.
Upvotes: 0
Views: 223
Reputation: 9203
This is an easy way to achieve what you want.
merged_str = { key: [str1[key]]+str2[key] for key in str2 }
BTW they are called dictionaries and not JSON strings.
Upvotes: 1
Reputation: 3608
Now is an working answer
def toList(x):
if isinstance(x, list):
return x
else:
return [x,]
s3 = {k:toList(s1[k])+ toList(s2[k]) for k in s1.keys()}
assuming same keys in both s1 and s2
Upvotes: 1