Compare if Two JSON files have same Data Regardless of Order in Python

The following Python code reads JSON data from two JSON files and checks if the data in these two different files are same or not. The code returns True if the data in both of the files are same regardless of the data order else it returns False. For example, {"Python", "Java", "C++", "Android"} and {"C++", "Android", "Java", "Python"} will return True.

First, we will read JSON data of two JSON files, sort the data in ascending order by keys and finally use the equal == operator to compare the sorted JSON data of the two files.

import json

#Reading JSON data from JSON files
file1 = open("D:\\file1.json", "r")
file2 = open("D:\\file2.json", "r")
json_data_file1 = json.load(file1)
json_data_file2 = json.load(file2)

#Sorting data
sorted_json_data_file1 = json.dumps(json_data_file1, sort_keys=True)
sorted_json_data_file2 = json.dumps(json_data_file2, sort_keys=True)
result = sorted_json_data_file1 == sorted_json_data_file2
print("Result = ", result)   

The above code will give the following output:

{"price": 200, "product": "laptop", "product_id": 1}
{"price": 200, "product": "laptop", "product_id": 1}
Result = True