How to merge two JSON objects in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To merge two JSON objects in Python, you can use the update() method to merge one dictionary into another. Since JSON objects are represented as Python dictionaries when loaded into memory, this method works nicely for merging JSON objects together.

Here’s an example:

import json

# Example JSON objects to merge
json_obj1 = '{"name": "John", "age": 30}'
json_obj2 = '{"city": "New York", "country": "USA"}'

# Parse the JSON objects into Python dictionaries
dict1 = json.loads(json_obj1)
dict2 = json.loads(json_obj2)

# Merge the dictionaries
dict1.update(dict2)

# Convert the merged dictionary back into JSON format
merged_json = json.dumps(dict1)

# Print the merged JSON object
print(merged_json)

In this example, we have two JSON objects that we want to merge together. We parse them into Python dictionaries using json.loads(), merge them together using the update() method, and then convert the merged dictionary back into JSON format using json.dumps(). The resulting merged JSON object is then printed to the console.

It’s worth noting that if the two JSON objects have overlapping keys, the values from the second JSON object will overwrite the values from the first JSON object when they are merged together. If you want to merge the objects without overwriting existing keys, you could instead use the copy() method to create a new dictionary that contains the key-value pairs from both dictionaries.

Tags: