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.

๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ jsoncomparison
jsoncomparison ยท PyPI
This package is designed to compare two objects with a JSON-like structure and data types.
      ยป pip install jsoncomparison
    
Published ย  May 17, 2021
Version ย  1.1.0
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 28, 2013
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
๐ŸŒ
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?

๐ŸŒ
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.โ€ฆ
๐ŸŒ
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"}' json_2 = '{"CEO":"Sandeep Jain", "Domain":"CS/IT","Name": "GFG","Class": "Website"}' # Converting string into Python dictionaries json_dict1 = json.loads(json_1) json_dict2 = json.loads(json_2) print(sorted(json_dict1.items()) == sorted(json_dict2.items()))
๐ŸŒ
The Coding Forums
thecodingforums.com โ€บ archive โ€บ archive โ€บ python
how to compare two json file line by line using python? | Python | Coding Forums
May 28, 2013 - 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= open('newData.json') lastJsonFile= open('version1.json') newLines = newJsonFile.readlines() print newLines sortedNew = sorted([repr(x) for x in...
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
Medium
medium.com โ€บ @abedmaatalla โ€บ compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - If two json are not equal then find the exact difference. Comparing json is quite simple, we can use โ€˜==โ€™ operator,
๐ŸŒ
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.
๐ŸŒ
Real Python
realpython.com โ€บ python-json
Working With JSON Data in Python โ€“ Real Python
August 20, 2025 - When you deserialize a JSON file as a Python object, then you can interact with it nativelyโ€”for example, by accessing the value of the "name" key with square bracket notation ([]). Still, thereโ€™s a word of caution here. Import the original dog_data dictionary from before and compare it to frie_data:
๐ŸŒ
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 ๐Ÿ˜‚
๐ŸŒ
Quora
quora.com โ€บ How-do-I-compare-JSON-and-CSV-data-files-in-Python
How to compare JSON and CSV data files in Python - Quora
Answer (1 of 4): Without actual content of both files, can not suggest any easy way. But the idea would be to convert JSON to CSV and compare using Panda or other such libraries. Better would be to post the question on stack overflow with sample filesโ€ฆ
๐ŸŒ
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 - This article explores three effective methods for comparing JSON objects regardless of their order. The simplest approach is converting JSON strings to Python dictionaries and comparing them directly.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ json-files-compare
json-files-compare ยท PyPI
February 5, 2023 - Json-compare is a simple package that allows you to easily and fastly compare two .json files. Support key and multi-key comparison.
      ยป pip install json-files-compare
    
Published ย  Feb 05, 2023
Version ย  1.0.1
๐ŸŒ
Readthedocs
recursive-diff.readthedocs.io
recursive_diff: Compare two Python data structures โ€” recursive_diff 1.3.1.dev4+g93bfe0bae.d20251230 documentation
Again, it is very frequently needed to identify where differences are, and apply tolerance to the comparison. This module offers the function recursive_diff(), which crawls through two arbitrarily large nested JSON-like structures and dumps out all the differences. Python-specific data types, such as set and tuple, are also supported.
๐ŸŒ
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 - Congratulations! You've successfully created an advanced JSON diff checker in Python using the deepdiff and termcolor libraries. You've learned how to compare JSON objects with precision and present the results in a user-friendly and visually appealing format.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ json.html
json โ€” JSON encoder and decoder
February 23, 2026 - If sort_keys is true (default: False), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
๐ŸŒ
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 โ€บ 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