0

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.

2
  • Can you post print for the three strings? Commented Mar 2, 2017 at 12:39
  • The Json your provided is not in the same format, what if you have two string1 with different value on Value? What's supposed to be the output? Commented Mar 2, 2017 at 12:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

OP has specifically mentioned that string2 has the list.
Thanks, this method worked for me, and looked to be the simplest solution
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.