Compare Two JSON files in Python

To compare if two JSON files have the same data regardless of the order in Python, you can use the following approach. This method works for JSON objects (dictionaries) and JSON arrays (lists) within the files:

  1. Read and parse the JSON data from both files.
  2. Sort the data within each JSON object (if present) or JSON array (if present) based on keys (for dictionaries) or item values (for lists).
  3. Compare the sorted JSON data to determine if they are equal.

To demonstrate how to compare two JSON files with unordered data, Here's an example with two JSON files and a Python script to compare them.

Here are two sample JSON files, file1.json and file2.json:

    "age": 30,
    "hobbies": ["swimming", "reading", "programming"],
    "name": "Alice"
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "swimming", "programming"]

Here's a Python code example:

import json

# Function to recursively sort JSON data
def sort_json(data):
    if isinstance(data, dict):
        return {key: sort_json(value) for key, value in data.items()}
    elif isinstance(data, list):
        return sorted([sort_json(item) for item in data])
        return data

# Read JSON data from two files
file1_path = "D:\\file1.json"
file2_path = "D:\\file2.json"

with open(file1_path, "r") as file1, open(file2_path, "r") as file2:
    json_data_file1 = json.load(file1)
    json_data_file2 = json.load(file2)

# Sort the JSON data
sorted_data_file1 = sort_json(json_data_file1)
sorted_data_file2 = sort_json(json_data_file2)

# Compare the sorted data
result = sorted_data_file1 == sorted_data_file2

# Print the result
if result:
    print("The JSON data in both files is the same.")
    print("The JSON data in the files is not the same.")

The output of the above code is as follows:

The JSON data in both files is the same.