1

I have two JSON I need some way to merge the unique values and overwrite the common key with the later value. Ordering doesn't really matter as long as the content can be produced.

JSON 1

{ "key": {"a": "1", "b": "2", "c": "3", "list": ["5", "6", "7"] } }

JSON 2

{ "key": {"b": "9", "list": ["8"] } }

Result JSON

{ "key": {"a": "1", "b": "9", "c": "3", "list": ["5", "6", "7", "8"] } }
2
  • 2
    Don't you need something recursive? Because it seems you don't always want to overwrite: if the value is a list, then the lists should be merged and not overwritten. Commented Apr 29, 2020 at 7:10
  • 1
    Do you have a specific question regarding your program? Please see How to Ask, help center. Commented Apr 29, 2020 at 7:56

1 Answer 1

1

Because you seem to want to keep some values and overwrite others, I have hastily cobbled together a recursive function that does that, barring some edge-cases.

def combine(dict1, dict2):
    """Updates dict1 to contain dict2"""
    for key in dict2:
        if key in dict1:
            if isinstance(dict1[key], list): # If value is a list, we want special logic
                if isinstance(dict2[key], list): # if the "input" is a list, just do list + list
                    dict1[key] = dict1[key] + dict2[key]
                else:
                    dict1[key].append(dict2[key])
            elif isinstance(dict1[key], dict): # calling itself recursively
                dict1[key] = combine(dict1[key], dict2[key])
            else: # Overwrites all other values
                dict1[key] = dict2[key]
        else: # Creates the values that doesn't exist.
            dict1[key] = dict2[key]
    return dict1

It's a mess and nigh unreadable. Anyway, here is a demonstration:

import json
json1 = '{ "key": {"a": "1", "b": "2", "c": "3", "list": ["5", "6", "7"] } }'
json2 = '{ "key": {"b": "9", "list": ["8"] } }'

json1 = json.loads(json1)
json2 = json.loads(json2)

print(json1) # {'key': {'a': '1', 'b': '2', 'c': '3', 'list': ['5', '6', '7']}}
print(json2) # {'key': {'b': '9', 'list': ['8']}}
print(combine(json1,json2)) # {'key': {'a': '1', 'b': '9', 'c': '3', 'list': ['5', '6', '7', '8']}}
Sign up to request clarification or add additional context in comments.

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.