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.

Discussions

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
Comparing Two JSON Files For Differences
Few words... Pandas, dataframe... More on reddit.com
🌐 r/learnpython
13
1
August 29, 2022
A good method for finding any differences between two json files?
So I have 2 json files that I need to compare, and after a certain known event there is an expected difference somewhere in the files, and I'm trying… More on reddit.com
🌐 r/learnpython
4
4
August 23, 2013
Best way to diff two JSON files and write differences data to third file?
The difflib module is a python standard module that has methods to help compare data, such as context_diff() or ndiff(). More on reddit.com
🌐 r/learnpython
7
1
August 20, 2017
🌐
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
🌐
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 - Programmatically, one can write ... writing code and all, This is where deepdiff comes in handy. Deepdiff is a powerful python library to compare 2 dictionaries....
🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
🌐
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.
      » pip install jsoncomparison
    
Published   May 17, 2021
Version   1.1.0
Find elsewhere
🌐
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.
Starred by 68 users
Forked by 23 users
Languages   Python 95.8% | Makefile 4.2%
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compare-json-objects-regardless-of-order-in-python
How to compare JSON objects regardless of order in Python? - GeeksforGeeks
July 23, 2025 - 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())) ... [('CEO', 'Sandeep Jain'), ('Class', 'Website'), ('Domain', 'CS/IT'), ('Name', 'GF
🌐
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 😂
🌐
Deviloper's Blog
deviloper.in › advanced-json-diff-checker-in-python-an-in-depth-guide
Advanced JSON Diff Checker in Python: An In-Depth Guide
September 9, 2024 - Here's how we can perform the ... by running: ... # Find differences between the two JSON objects diff = DeepDiff(json_obj1, json_obj2, ignore_order=True)...
🌐
Reddit
reddit.com › r/learnpython › comparing two json files for differences
r/learnpython on Reddit: Comparing Two JSON Files For Differences
August 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?

🌐
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} [...
🌐
Edureka Community
edureka.co › home › community › categories › python › how to compare two json objects with the same...
How to compare two JSON objects with the same elements in a different order equal | Edureka Community
August 7, 2020 - How can I test whether two JSON objects are equal in python, disregarding the order of lists? For ... the order of the "errors" lists are different.
🌐
TutorialsPoint
tutorialspoint.com › 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. ... The JSON objects are equal. The output of the code signifies that despite the elements of the two JSON objects being in different orders, they are equal.
🌐
CopyProgramming
copyprogramming.com › howto › python-compare-two-json-objects-and-get-difference
How to Compare Two JSON Objects in Python: The 2026 Guide & Best Practices - Python compare two json objects and get difference
December 15, 2025 - For simple use cases—where you just need to know if two objects are different, not how—Python’s standard library is sufficient. The Equality Operator () Python’s converts JSON objects into dictionaries. Since Python dictionaries are hash maps, the operator compares them by value, regardless of key insertion order.
🌐
PyPI
pypi.org › project › json-files-compare
json-files-compare · PyPI
February 5, 2023 - Here's an example: print(comparator.diff_log.get_summary()) # OUTPUT example: # --------------------- # TOTAL: 4 differences # -missing_obj_property: 3 # -unequal_value: 4 · Set key property to perform more accurate comparisons of objects in arrays: # expected.json: {"cats": [{"id": 4, "name": "Nyan"}, {"id": 2, "name": "Marx"}, {"id": 8, "name": "Flake"}]} # actual.json: {"cats": [{"id": 2, "name": "Marx"}, {"id": 4, "name": "Naan"}]} comparator = JSONComparator( left_file_path="expected.json", right_file_path="actual.json", key="DATA//cats//<array>//id", # <----- just pass a "path" to needed property with following keywords: ) # DATA - points to the root of file # <array> - indicates array with key property's object
      » pip install json-files-compare
    
Published   Feb 05, 2023
Version   1.0.1
🌐
Reddit
reddit.com › r/learnpython › a good method for finding any differences between two json files?
r/learnpython on Reddit: A good method for finding any differences between two json files?
August 23, 2013 - Edit: I just tested json_tools from pypi, and the diff works, but the function returns the whole json file instead of just the line that's different, not quite what I need I think. Second Edit: Found a solution that seems to work for me at the moment, posted below in response to indosauros. Share ... Subreddit for posting questions and asking for general advice about all topics related to learning python.
🌐
Djangosnippets
djangosnippets.org › snippets › 2247
djangosnippets: Comparing two json like python objects
October 31, 2010 - Shows properties, values from first object that are not in the second. ... Diff(first, second, vice_versa=True) gives you difference from both objects in the one result. df.difference is ["path: last_name", "path: pet_name"] Diff(first, second, with_values=True) gives you difference of the ...