Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to compare JSON objects regardless of order in Python?

How to compare JSON objects regardless of order in Python?

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

RELATED ARTICLES

Most Popular

Recent Comments