4

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?

ankur suman
  • 151
  • 1
  • 3
  • 10

3 Answers3

6

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)
Menglong Li
  • 2,177
  • 14
  • 19
4

json.dumps() converts a dictionary to str object, not a json(dict) object.

So, adding some dumps statement in your code shows that the type is changed to str after using json.dumps() and with + you are effectively concatenating the two string and hence you get the concatenated output.

Further, to merge the two dictionaries for your simple case, you can just use the append:

import json

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

print(type(json_obj1))  # the type is `str`

json_obj += json_obj1   # this concatenates the two str objects

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

json_obj["a"].extend(json_obj1["a"])
 
print(json_obj)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
3

I suggest you to study basic fundamental of Python for your own sake as you don't seem to understand why your code wouldn't work.

import json

# We have two dictionaries to combine
json_obj_1 = {"a": [1,2], "b":[2,3], 'c': [1,2,3]}
json_obj_2 = {"a": [3,4], 'd':[4,2], 'e': [4,2,2]}

Merged dictionary will be stored here

hold_json_obj = {}

Don't worry, it's not actually that complicated. Read the code line by line with comments attached and you'll understand.

# We'll loop through every item in the json_obj_1 dictionary
for item_1 in json_obj_1:
    # We'll also loop through every item in the json_obj_2 dictionary
    for item_2 in json_obj_2:
        # Now let's compare whether they are the same KEYS (not values)
        if item_1 == item_2:
            # if they match, we create a list to store the array
            hold_array = []
            hold_array.extend(json_obj_1[item_1])
            hold_array.extend(json_obj_2[item_1])
            
            # finally putting the array to our hold_json_obj
            hold_json_obj[item_1] = hold_array
        else:
            # if they don't match, check if the key already exists in the
            # hold_json_obj because we might be iterating json_obj_2 for the second time.
            if item_2 not in hold_json_obj:
                #add the ummatched array to hold_json_obj
                hold_json_obj[item_2] = json_obj_2[item_2]

Now simply update json_obj_1 with the update method. The update function is required because if json_obj_1 has keys that json_obj_2 doesn't then we may have missed them out in the above loops.

json_obj_1.update(hold_json_obj)
print(json_obj_1)

This is what the print displays.

{'a': [1, 2, 3, 4], 'b': [2, 3], 'c': [1, 2, 3], 'd': [4, 2], 'e': [4, 2, 2]}
Ali Raz
  • 31
  • 3