pythonjsonpython-3.x

Merge two json object in python


I am merging two json in python

I'm doing

import json

json_obj = json.dumps({"a": [1,2]})
json_obj1 = json.dumps({"a": [3,4]})

json_obj += json_obj1

print(json_obj)

I am expecting the output as

{"a": [1, 2,3,4]}

but i got

{"a": [1, 2]}{"a": [3, 4]}

How to get the earlier one?


Solution

  • In json module, dumps convert python object to a string, and loads convert a string into python object. So in your original codes, you just try to concat two json-string. Try to code like this:

    import json
    
    from collections import defaultdict
    
    
    def merge_dict(d1, d2):
        dd = defaultdict(list)
    
        for d in (d1, d2):
            for key, value in d.items():
                if isinstance(value, list):
                    dd[key].extend(value)
                else:
                    dd[key].append(value)
        return dict(dd)
    
    
    if __name__ == '__main__':
        json_str1 = json.dumps({"a": [1, 2]})
        json_str2 = json.dumps({"a": [3, 4]})
    
        dct1 = json.loads(json_str1)
        dct2 = json.loads(json_str2)
        combined_dct = merge_dict(dct1, dct2)
    
        json_str3 = json.dumps(combined_dct)
    
        # {"a": [1, 2, 3, 4]}
        print(json_str3)