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
๐ŸŒ
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.
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

A good method for finding any differences between two json files?
Subreddit for posting questions and asking for general advice about all topics related to learning python. ... 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 to verify what that difference ... More on reddit.com
๐ŸŒ r/learnpython
4
4
August 23, 2013
python - Comparison of JSON file key values - Stack Overflow
There are two JSON files with keys and values. You need to compare "key1" of two files and if the values are equal, then make a difference between the values of "key 2" of two f... 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
JSON and Dictionary
The core of your answer is correct: JSON is some string representation of data dicts are objects in memory But your explanations are geting away from these facts. 1. Comparing notation dicts are not strings! You say that dicts are represented by "curly braces" . So you are comparing json with dict representation, not dicts themselves. my_dict = dict('name' = 'eagle221b', 'platform' = 'reddit') This is another representation of dicts, that does not look like JSOn at all. Also you are saying "curly braces"in JSON are objects. No they are representations of objects. This makes a great difference when working with them. 2. the power of dicts So let me create another example again: my_list = [] my_dict1 = {'my_list': my_list} my_dict2 = {'my_list': my_list} my_list.append('foo') The last command has not changed any of the dicts, but if you print them, you will see the representation has changed. Also about the values: you can store objects or even functions in them. A value in dicts is just a memory pointer. (and yes, any number in python is an object) Conclusion They both are completly different things that both are based on a key value principle. But one is a text, one is memory and therefore very different. More on reddit.com
๐ŸŒ r/Python
49
250
October 8, 2020
๐ŸŒ
GitHub
github.com โ€บ rugleb โ€บ JsonCompare
GitHub - rugleb/JsonCompare: The Python JSON Comparison package ยท GitHub
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%
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ json-diff
json-diff ยท PyPI
Compares two JSON files ... 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
gist.github.com โ€บ magnetikonline โ€บ 845400198a8e4e4648746a675e955af3
comparing JSON data structures. - Python - Gist - GitHub
I'm sorry, but it's not same that if '==' betwen two json? I think that would be better return what key or value is different. ... you might want to sort the lists before comparing them, and length of dictionaries could be compared as well
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ jsoncomparison
jsoncomparison ยท PyPI
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
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @abedmaatalla โ€บ compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - Consider below example, jsn_1 contains three items with keys โ€˜aโ€™,โ€™bโ€™,โ€™cโ€™ respectively, in jsn_2 below changes has been done: ... DeepDiff function of deepdiff module returns all the changes, let's find all differences using deepdiff: Output: result is a dictionary which contains all differences. ... We have seen easiest way to compare and find the differences in json objects.
๐ŸŒ
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 - Would a method checking if the key/value is a dict and then recursively calling itself if it is, otherwise do a comparison, be a decent solution to that? Or does anyone else have an idea? This is a short sample of the json I'd be testing with, I'd need to be able to identify a difference in the 'general_consumer" entry as well as the top level ones.
๐ŸŒ
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 - So, in such cases we can define a custom function ourselves that can recursively sort any list or dictionary (by converting dictionaries into a list of key-value pair) and thus they can be made fit for comparison. Implementation using this alternative is given below. Example: Python3 ยท 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 dict
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ json-files-compare
json-files-compare ยท PyPI
February 5, 2023 - 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
๐ŸŒ
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 first ... by calling the dumps method with the sort_keys=True parameter. Finally, we compare the sorted JSON objects using the == operator....
๐ŸŒ
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} [...
๐ŸŒ
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 - We use DeepDiff to compare these JSON objects and store the differences in the diff variable. We create a colorize function to apply color coding to our output using termcolor. We iterate through the categories of differences (added keys, removed ...
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-com-pare-json-objects
Comparing JSON Objects in Python - CodeRivers
March 3, 2025 - Python's built-in == operator can be used to compare two JSON-like Python objects (dictionaries or lists). This operator performs a shallow comparison, meaning it checks if the top-level keys and values are equal.
๐ŸŒ
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%
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70563086 โ€บ comparison-of-json-file-key-values
python - Comparison of JSON file key values - Stack Overflow
with open('file1.json') as f, open('file2.json') as f2: json1 = json.load(f) json2 = json.load(f2) json1_dict = {} for json_obj in json1: json1_dict[json_obj['key1']] = int(json_obj['key2']) json2_dict = {} for json_obj in json2: json2_dict[json_obj['data'][0]['key1']] = int(json_obj['data'][0]['key2']) for key in json1_dict: if key in json2_dict: print(f"diff: {json1_dict[key] - json2_dict[key]}")
๐ŸŒ
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 ๐Ÿ˜‚
๐ŸŒ
Djangosnippets
djangosnippets.org โ€บ snippets โ€บ 2247
djangosnippets: Comparing two json like python objects
October 31, 2010 - For lists, you might use set(enumerate(list1)) - set(enumerate(list2)). Now generalize the mapper and use set(mapper(json1)) - set(mapper(json2)). No need for 66 lines, which are completely unrelated to Django. ... I think it's good, but not for all cases. We need to check keys only (does the both have "f" key):