How to compare JSON objects regardless of order in Python? - GeeksforGeeks

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 stringjson_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 dictionariesjson_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 stringjson_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 dictionaryjson1_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 stringjson_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 dictionaryjson1_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
Picked
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python