How to compare JSON objects regardless of order in Python?
Last Updated :
24 Jan, 2021
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primarily for data transmission between server and web applications. .
In this article, we will be learning about how can we compare JSON objects regardless of the order in which they exist in Python.
Approach:
- Import module
- Create JSON strings
- Convert strings to python dictionaries
- Sort dictionaries
- Compare
- Print result
Various implementation to do the same is given below,
Example 1: Using sorted()
Python3
import json
# JSON string
json_1 = '{"Name":"GFG", "Class": "Website", "Domain":"CS/IT", "CEO":"Sandeep Jain"}'
json_2 = '{"CEO":"Sandeep Jain", "Domain":"CS/IT","Name": "GFG","Class": "Website"}'
# Converting string into Python dictionaries
json_dict1 = json.loads(json_1)
json_dict2 = json.loads(json_2)
print(sorted(json_dict1.items()) == sorted(json_dict2.items()))
Output:
True
Example 2: More complex comparison
Python3
import json
# JSON string
json_1 = '{"Name":"GFG", "Class": "Website", "Domain":"CS/IT", "CEO":"Sandeep Jain","Subjects":["DSA","Python","C++","Java"]}'
json_2 = '{"CEO":"Sandeep Jain","Subjects":["C++","Python","DSA","Java"], "Domain":"CS/IT","Name": "GFG","Class": "Website"}'
# Convert string into Python dictionary
json1_dict = json.loads(json_1)
json2_dict = json.loads(json_2)
print(sorted(json1_dict.items()) == sorted(json2_dict.items()))
print(sorted(json1_dict.items()))
print(sorted(json2_dict.items()))
Output:
False
[('CEO', 'Sandeep Jain'), ('Class', 'Website'), ('Domain', 'CS/IT'), ('Name', 'GFG'), ('Subjects', ['DSA', 'Python', 'C++', 'Java'])]
[('CEO', 'Sandeep Jain'), ('Class', 'Website'), ('Domain', 'CS/IT'), ('Name', 'GFG'), ('Subjects', ['C++', 'Python', 'DSA', 'Java'])]
In this case we get our result as False because the problem with sorted() method is it only works on the top-level of a dictionary i.e., onto the keys and not on their values as can be verified by above code. So, in such cases we can define a custom function ourselves that can recursively sort any list or dictionary (by converting dictionaries into a list of key-value pair) and thus they can be made fit for comparison. Implementation using this alternative is given below.
Example:
Python3
import json
# JSON string
json_1 = '{"Name":"GFG", "Class": "Website", "Domain":"CS/IT", "CEO":"Sandeep Jain","Subjects":["DSA","Python","C++","Java"]}'
json_2 = '{"CEO":"Sandeep Jain","Subjects":["C++","Python","DSA","Java"], "Domain":"CS/IT","Name": "GFG","Class": "Website"}'
# Convert string into Python dictionary
json1_dict = json.loads(json_1)
json2_dict = json.loads(json_2)
def sorting(item):
if isinstance(item, dict):
return sorted((key, sorting(values)) for key, values in item.items())
if isinstance(item, list):
return sorted(sorting(x) for x in item)
else:
return item
print(sorting(json1_dict) == sorting(json2_dict))
Output:
True
Similar Reads
How to Compare Objects in JavaScript? Comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations. Below are the various approaches to co
3 min read
How to Compare List of Dictionaries in Python Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read
How to JSON decode in Python? When working with JSON data in Python, we often need to convert it into native Python objects. This process is known as decoding or deserializing. The json module in Python provides several functions to work with JSON data, and one of the essential tools is the json.JSONDecoder() method. This method
5 min read
Deserialize JSON to Object in Python Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module
2 min read
How to Parse Data From JSON into Python? The json module in Python provides an easy way to convert JSON data into Python objects. It enables the parsing of JSON strings or files into Python's data structures like dictionaries. This is helpful when you need to process JSON data, which is commonly used in APIs, web applications, and configur
1 min read
How to Sort JSON Object Arrays Based on a Key? Sorting is the process of arranging elements in a specific order. In JavaScript, we can sort a JSON array by key using various methods, such as the sort() function. Along with this, we can use various other approaches and methods that are implemented in this article. Below are the approaches to sort
3 min read