If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True
Answer from Zero Piraeus on Stack Overflow
Top answer
1 of 12
225

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True
2 of 12
94

Another way could be to use json.dumps(X, sort_keys=True) option:

import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison

This works for nested dictionaries and lists.

🌐
Reddit
reddit.com › r/learnpython › comparing two json files for differences
r/learnpython on Reddit: Comparing Two JSON Files For Differences
July 29, 2022 -

I need to compare two JSON files that contain a list of dictionaries whose basic format is:

[{"protocol": "S", "type": "", "network": "0.0.0.0", "mask": "0", "distance": "254", "metric": "0", "nexthop_ip": "192.168.122.1", "nexthop_if": "", "uptime": ""}, {"protocol": "O", "type": "", "network": "10.129.30.0", "mask": "24", "distance": "110", "metric": "2", "nexthop_ip": "172.20.10.1", "nexthop_if": "GigabitEthernet0/1", "uptime": "08:58:25"}]

Though there are many, many more dictionary items in the list than that shown above. I am not quite sure how best to go about comparing the files to spot differences and return or save those difference to another file, preferably in JSON format, though a CSV would be fine too.

The one gotcha that there may be is I need to exclude, at a minimum, the uptime value as it is constantly changing so it will of course trigger anything looking for changes. Can anyone help get me started please?

Discussions

Is there a way to compare two JSON files/json body?
I have so far failed to do such a thing - compare entire json files. Tried with RequestsLibrary, JSONlibrary, Collections working in unison, there is a always some error… It can be a simple one like on jsonplaceholder.typicode.com/todos/1 If anyone has a suggestion, please 🙂 More on forum.robotframework.org
🌐 forum.robotframework.org
0
0
May 13, 2025
how to compare two json file line by line using python?
hi, how to compare two json file line by line using python? Actually I am doing it in this way.. import simplejson as json def compare(): newJsonFile=... More on thecodingforums.com
🌐 thecodingforums.com
6
May 27, 2013
python - Compare two JSON Files and Return the Difference - Stack Overflow
1 How to compare two json files disregarding a certain key · 3 Python compare two json file and get only the difference · 0 Find difference between two json files in python More on stackoverflow.com
🌐 stackoverflow.com
Diff two large JSON array or objects
Yes Firstly you have to load json data in python dictionary using json module/package After that jsondiff module/package help you check different This module/package also compare list,set,etc.👌 If will return empty dictionary {} if there is no different👍 import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson) if r : print(r) else: print("404,No Different Found!") Output: {1: 1, 4: 4, delete: [2, 3]} 😀 json.diff take 1st arg oldJson means from which we are checking different & 2nd newJson. There are 3 syntax 🎲 : compact ( default ) Any Change in Value of key & new insrted key will display normaly symmetric Inserted & delete show differently change show normally explicit 👀 It is detailed Inserted Deleted Changed Show differently import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print(r) else: print("404,No Different Found!") Output : {insert: {4: 4}, update: {1: 1}, delete: [2, 3]} 😃 Finally 🔥,Now you doubt about how to access them You can access them using symbols eg. r[jsondiff.symbols.insert] OR from jsondiff import symbols r[symbols.insert] There are some other symbols which use in different compare like list,set, etc Note : if you try using insert in compact & update in compact & symmetric then you will get KeyError 😔 because those not exist there import jsondiff from jsondiff import symbols oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print("Deleted keys are ",r[symbols.delete]) else: print("404,No Different Found!") Output : Deleted keys are [2, 3] 🥳 Thanks for reading 😂 More on reddit.com
🌐 r/learnpython
3
3
February 26, 2022
🌐
PyPI
pypi.org › project › json-files-compare
json-files-compare · PyPI
February 5, 2023 - You can go further and add non-important fields to ignore parameter: # expected.json: [{"id": 4, "name": "Nyan", "age": 2}, {"id": 2, "name": "Marx", "age": 7}, {"id": 8, "name": "Flake", "age": 4}] # actual.json: [{"id": 2, "name": "Marx", "age": 7}, {"id": 4, "name": "Naan", "age": "two"}, {"id": 9, "name": "Lol", "age": 1}] comparator = JSONComparator( left_file_path="expected.json", right_file_path="actual.json", key="DATA//<array>//id", ignore="DATA//<array>//age" # <------- )
      » pip install json-files-compare
    
Published   Feb 05, 2023
Version   1.0.1
🌐
Quora
quora.com › How-do-I-compare-two-JSON-files-in-Python
How to compare two JSON files in Python - Quora
Answer (1 of 5): In Python, the [code ]==[/code] operator is recursive. So if you read in two JSON files, you can compare them like this: [code]doc1 == doc2 [/code]In python, key ordering is preserved, so these two will be printed differently: [code]d1 = {'a': 3, 'b': 4} d2 = {'b': 4, 'a': 3} [...
🌐
GitHub
github.com › monsur › jsoncompare
GitHub - monsur/jsoncompare: A simple utility to compare two JSON objects.
jsoncompare is a simple Python utility for comparing two JSON objects USAGE python jsoncompare.py <item1> <item2> Where item1 and item2 are either a file or a url containing a JSON object.
Starred by 22 users
Forked by 27 users
Languages   Python 100.0% | Python 100.0%
🌐
Medium
medium.com › @abedmaatalla › compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - Comparing json is quite simple, we can use ‘==’ operator, Note: ‘==’ and ‘is’ operator are not same, ‘==’ operator is use to check equality of values , whereas ‘is’ operator is used to check reference equality, hence one should use ‘==’ operator, ‘is’ operator will not give expected result. Comparing two dictionaries has been solved in the first part of this articles.
🌐
GitHub
github.com › cpatrickalves › json-diff
GitHub - cpatrickalves/json-diff: A Python script that compares two JSON files and shows their differences.
A Python script that compares two JSON files and shows their differences. - cpatrickalves/json-diff
Author   cpatrickalves
Find elsewhere
🌐
PyPI
pypi.org › project › json-diff
json-diff · PyPI
Compares two JSON files (http://json.org) and generates a new JSON file with the result. Allows exclusion of some keys from the comparison, or in other way to include only some keys. The project’s website is at https://gitlab.com/mcepl/json_diff Patches and pull requests are welcome, but please keep the script compatible with python 2.4.
      » pip install json-diff
    
Published   Aug 25, 2019
Version   1.5.0
🌐
PyPI
pypi.org › project › jsoncomparison
jsoncomparison · PyPI
First you need to define two variables: expected & actual. Think of them as the same variables that you use in tests. Expected - the original data object that you want to see. Actual - the given data object. Then we will transfer these objects to check and identify the difference between them: from jsoncomparison import Compare, NO_DIFF expected = { "project": { "name": "jsoncomparison", "version": "0.1", "license": "MIT", "language": { "name": "python", "versions": [ 3.5, 3.6 ] } }, "os": "linux" } actual = { "project": { "name": "jsoncomparison", "version": 0.1, "license": "Apache 2.0", "language": { "name": "python", "versions": [ 3.6 ] } } } diff = Compare().check(expected, actual) assert diff != NO_DIFF
      » pip install jsoncomparison
    
Published   May 17, 2021
Version   1.1.0
🌐
Keploy
keploy.io › home › community › how to compare two json files?
How to compare two JSON files? | Keploy Blog
June 9, 2024 - Find differences between two JSON files using Python, VS Code, and free online JSON diff tools. Ideal for developers and testers.
🌐
GitHub
gist.github.com › magnetikonline › 845400198a8e4e4648746a675e955af3
comparing JSON data structures. - Python - Gist - GitHub
... A function compare_json_data(source_data_a,source_data_b), accepting structures populated with data loaded from json.load() and comparing for equality. ... JSON files a.json and b.json are loaded via load_json() function and structures passed into compare_json_data() for comparison...
🌐
YouTube
youtube.com › watch
Compare Two JSON Files in Python | 5 different ways to compare two json in python - YouTube
Hello learner,In this video, you will learn how to compare and check if two json files are identical. And if they are different, what is the actual differenc...
Published   November 26, 2024
🌐
GitHub
github.com › rugleb › JsonCompare
GitHub - rugleb/JsonCompare: The Python JSON Comparison package · GitHub
First you need to define two variables: expected & actual. Think of them as the same variables that you use in tests. Expected - the original data object that you want to see. Actual - the given data object. Then we will transfer these objects to check and identify the difference between them: from jsoncomparison import Compare, NO_DIFF expected = { "project": { "name": "jsoncomparison", "version": "0.1", "license": "MIT", "language": { "name": "python", "versions": [ 3.5, 3.6 ] } }, "os": "linux" } actual = { "project": { "name": "jsoncomparison", "version": 0.1, "license": "Apache 2.0", "language": { "name": "python", "versions": [ 3.6 ] } } } diff = Compare().check(expected, actual) assert diff != NO_DIFF
Starred by 68 users
Forked by 23 users
Languages   Python 95.8% | Makefile 4.2%
🌐
Robot Framework
forum.robotframework.org › libraries › jsonlibrary
Is there a way to compare two JSON files/json body? - JSONLibrary - Robot Framework
May 13, 2025 - I have so far failed to do such a thing - compare entire json files. Tried with RequestsLibrary, JSONlibrary, Collections working in unison, there is a always some error… It can be a simple one like on jsonplaceholder.…
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
how to compare two json file line by line using python? | Python | Coding Forums
May 27, 2013 - Actually I am doing it in this way.. import simplejson as json def compare(): newJsonFile= open('newData.json') lastJsonFile= open('version1.json') newLines = newJsonFile.readlines() print newLines sortedNew = sorted([repr(x) for x in...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-compare-json-objects-regardless-of-order-in-python
How to compare JSON objects regardless of order in Python? - GeeksforGeeks
January 24, 2021 - For example, if you're working with APIs, you might return a JSON response using frameworks like Flask. Let's explore sever ... In Python, both is and == are used for comparison, but they serve different purposes:== (Equality Operator) → Compares values of two objects.is (Identity Operator) → Compares memory location of two objects.Pythona = [1,2,3] b = [1,2,3] print(a == b) print(a is b) OutputTrue False Explanation: a and
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-compare-json-objects-regardless-of-order-in-python
How to Compare JSON Objects Regardless of Order in Python?
July 20, 2023 - In the above example, we utilized the json.loads method provided by Python's built?in json module to convert the JSON objects json_obj1 and json_obj2 to dictionaries. subsequently, we compared the two dictionaries using the == operator.
🌐
Reddit
reddit.com › r/learnpython › diff two large json array or objects
r/learnpython on Reddit: Diff two large JSON array or objects
February 26, 2022 -

I have a Python lambda function downloading a large excel file and converting it to JSON.

This file will be downloaded at least once a day (as the data can change)

I need to push the changed/updated data to an API.

Is there a way for me to compare two JSON files and output the diff?

It would be perfect if it would output multiple arrays of objects.

1 array of objects that have changed (I don’t care what has changed, just need to know that it has)

1 array of removed/deleted objects.

Top answer
1 of 1
4
Yes Firstly you have to load json data in python dictionary using json module/package After that jsondiff module/package help you check different This module/package also compare list,set,etc.👌 If will return empty dictionary {} if there is no different👍 import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson) if r : print(r) else: print("404,No Different Found!") Output: {1: 1, 4: 4, delete: [2, 3]} 😀 json.diff take 1st arg oldJson means from which we are checking different & 2nd newJson. There are 3 syntax 🎲 : compact ( default ) Any Change in Value of key & new insrted key will display normaly symmetric Inserted & delete show differently change show normally explicit 👀 It is detailed Inserted Deleted Changed Show differently import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print(r) else: print("404,No Different Found!") Output : {insert: {4: 4}, update: {1: 1}, delete: [2, 3]} 😃 Finally 🔥,Now you doubt about how to access them You can access them using symbols eg. r[jsondiff.symbols.insert] OR from jsondiff import symbols r[symbols.insert] There are some other symbols which use in different compare like list,set, etc Note : if you try using insert in compact & update in compact & symmetric then you will get KeyError 😔 because those not exist there import jsondiff from jsondiff import symbols oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print("Deleted keys are ",r[symbols.delete]) else: print("404,No Different Found!") Output : Deleted keys are [2, 3] 🥳 Thanks for reading 😂