Python Examples
Convert IP to Integer and Integer To IP in Python How to Get IPv4/IPv6 Address Range from CIDR in Python? Compare Two Objects For Equality in Python How to find Duplicate Elements from a List in Python Convert Timestamp to datetime in Python Convert datetime to Timestamp in Python Generate Random String of Specific Length in Python Encryption and Decryption of Strings in Python The string module in Python Convert string to bytes in Python Convert bytes to string in Python Convert string to datetime and datetime to string in Python Call a function Asynchronously from within a Loop and wait for the Results in Python Remove Duplicate Elements from a List in Python Caching in Python with Examples How to Bulk Insert and Retrieve Data from Redis in Python How to Write Unit Test in Python Read and Write CSV Files in Python Read and Write Data to a Text File in Python How to Convert CSV to JSON in Python Create ICS Calendar File in Python Install Python on Windows 10/11 Install Python on Ubuntu 20.04 or 22.04.3 Python - Install Virtual Environment How to Find a Specific Field Value from a JSON list in Python Download and Unzip a Zipped File in Python Python Install PIP Python Install Virtual Environment How to Fix Python Error: string argument without an encoding Compare Two JSON files in Python How to Hash a Dictionary Object in Python? Create a Digital Clock in Python Create Multiple URLs Using Each Path of a URL in Python Send an Email with Multiple Attachments using Amazon SES in Python SQLAlchemy Query Examples for Effective Database Management SQLAlchemy Query to Find IP Addresses from an IP Range in Bulk How to Create and Use Configuration files in a Python Project Check if a Value Already Exists in a List of Dictionary Objects in Python How to Split Large Files by size in Python? Fixing - Running Scripts is Disabled on this System Error on Windows Generating QR Codes in Python Reading QR Codes in Python

Compare Two JSON files in Python

  • Last updated Apr 25, 2024

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])
    else:
        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.")
else:
    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.