How to merge two JSON objects in Python [5 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# Table of Contents

  1. How to merge two JSON objects in Python
  2. How to merge two JSON objects in Python using a dict comprehension
  3. Merge two JSON objects and write the merged dictionary to a File

# How to merge two JSON objects in Python

To merge two JSON objects in Python:

  1. Use the json.loads() method to parse the JSON objects into Python dictionaries.
  2. Use the dictionary unpacking operator to merge the two dictionaries.
main.py
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)

merge two json objects

The code for this article is available on GitHub

You can also shorten this a bit if you don't need to assign the dictionaries to variables.

main.py
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.

main.py
import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) print(obj1) # ๐Ÿ‘‰๏ธ '{"id": 1, "name": "bobby hadz"}' print(type(obj1)) # ๐Ÿ‘‰๏ธ <class 'str'>
The code for this article is available on GitHub

We used the json.loads() method to convert the JSON strings to Python dictionaries.

main.py
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.

main.py
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 code for this article is available on GitHub

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.

main.py
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.

main.py
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.

# How to merge two JSON objects in Python using a dict comprehension

You can also use a dict comprehension to merge the two dictionaries.

main.py
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)

merge two json objects using dict comprehension

The code for this article is available on GitHub

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.

main.py
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.

main.py
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)
The code for this article is available on GitHub

# Merge two JSON objects and write the merged dictionary to a File

If you need to merge two JSON objects and write the merged dictionary to a file:

  1. Use the json.loads() method to parse the JSON objects into Python dictionaries.
  2. Use the dictionary unpacking operator to merge the two dictionaries.
  3. Use the json.dump() method to write the merged dictionary to a file.
main.py
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)

merge two json objects write merged dict to file

The code for this article is available on GitHub

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.

write merged json to file

You can also set the indent keyword argument if you want to pretty print the merged JSON object.

main.py
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)

pretty print merged json

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.

main.py
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 )
The code for this article is available on GitHub

When sort_keys is set to True, the output of dictionaries is sorted by key.

The argument defaults to False.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev