Last updated: Apr 11, 2024
Reading timeยท4 min
To merge two JSON objects in Python:
json.loads()
method to parse the JSON objects into Python
dictionaries.import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(merged_dict)
You can also shorten this a bit if you don't need to assign the dictionaries to variables.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) merged_dict = {**json.loads(obj1), **json.loads(obj2)} # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(merged_dict)
The json.dumps() method converts a Python object to a JSON formatted string.
Therefore the obj1
and obj2
variables store two JSON strings.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) print(obj1) # ๐๏ธ '{"id": 1, "name": "bobby hadz"}' print(type(obj1)) # ๐๏ธ <class 'str'>
We used the json.loads() method to convert the JSON strings to Python dictionaries.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) print(obj1) # ๐๏ธ {"id": 1, "name": "bobby hadz"} print(type(obj1)) # ๐๏ธ <class 'str'> print(json.loads(obj1)) # ๐๏ธ {'id': 1, 'name': 'bobby hadz'} print(type(json.loads(obj1))) # ๐๏ธ <class 'dict'>
The last step is to use the dictionary unpacking **
operator to merge the two
dictionaries.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(merged_dict)
If the two dictionaries have keys that clash, the values in dict2
will take
precedence because it comes after dict1
.
You can also add new key-value pairs to the dictionary if necessary.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2, 'salary': 1500, 'job': 'programmer'} # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', # 'topic': 'Python', 'salary': 1500, 'job': 'programmer'} print(merged_dict)
If you use a Python version greater than 3.9
, you can also use the merge |
operator to merge dictionaries.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = dict1 | dict2 # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(merged_dict)
The pipe |
symbol merges the two dictionaries in the example.
You can also use a dict comprehension to merge the two dictionaries.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = { key: value for (key, value) in list(dict1.items()) + list(dict2.items()) } # ๐๏ธ {'id': 1, 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(merged_dict)
Dict comprehensions are very similar to list comprehensions.
They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.
If you need to exclude certain keys when merging, use an if
statement.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = { key: value for (key, value) in list(dict1.items()) + list(dict2.items()) if key not in ('topic', 'id') } # ๐๏ธ {'name': 'bobby hadz', 'site': 'bobbyhadz.com'} print(merged_dict)
We used the not in
operator to exclude the topic
and id
keys when merging
the dictionaries.
The same can be achieved by using a simple for
loop.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {} for (key, value) in list(dict1.items()) + list(dict2.items()): if key not in ('topic', 'id'): merged_dict[key] = value # ๐๏ธ {'name': 'bobby hadz', 'site': 'bobbyhadz.com'} print(merged_dict)
If you need to merge two JSON objects and write the merged dictionary to a file:
json.loads()
method to parse the JSON objects into Python
dictionaries.json.dump()
method to write the merged dictionary to a file.import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} print(merged_dict) with open('data.json', 'w', encoding='utf-8') as f: json.dump(merged_dict, f)
We used the with
statement to open a data.json
file for writing.
The json.dump() method serializes the supplied object as a JSON formatted stream and writes it to a file.
On the other hand, the json.dumps()
method simply converts a Python object to
a JSON string.
Running the code sample with python main.py
produces the following data.json
file.
You can also set the indent
keyword argument if you want to pretty print the
merged JSON object.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} print(merged_dict) with open('data.json', 'w', encoding='utf-8') as f: json.dump(merged_dict, f, indent=4, ensure_ascii=False)
The indent
keyword argument is used to specify the indentation.
When the ensure_ascii
keyword argument is set to True
(the default), the
output is guaranteed to have all non-ASCII characters escaped.
If ensure_ascii
is False
, non-ASCII characters are output as is.
If you also want to sort the keys in the merged object, set the sort_keys
keyword argument to True
.
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} print(merged_dict) with open('data.json', 'w', encoding='utf-8') as f: json.dump( merged_dict, f, indent=4, ensure_ascii=False, sort_keys=True )
When sort_keys
is set to True
, the output of dictionaries is sorted by key.
The argument defaults to False
.
You can learn more about the related topics by checking out the following tutorials: