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
224

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.

🌐
TutorialsPoint
tutorialspoint.com › how-to-compare-json-objects-regardless-of-order-in-python
How to Compare JSON Objects Regardless of Order in Python?
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.
🌐
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.
🌐
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 - In this article, we will be learning about how can we compare JSON objects regardless of the order in which they exist in Python.
Top answer
1 of 3
21

Check out this python library jsondiff , that will help you to identify the diff's

import json

import jsondiff

json1 = json.loads(
    '{"isDynamic": false, "name": "", "value": "SID:<sid>", "description": "instance","argsOrder": 1,"isMultiSelect": false}')

json2 = json.loads(
    '{ "name": "", "value": "SID:<sid>","isDynamic": false, "description": "instance","argsOrder": 1,"isMultiSelect": false}')

res = jsondiff.diff(json1, json2)
if res:
    print("Diff found")
else:
    print("Same")
2 of 3
6

UPDATED: See https://eggachecat.github.io/jycm-json-diff-viewer/ for a live demo! Now it has a JS-native implementation.

Affiliation: I am the author of this lib.

Yes! You can diff it with jycm which has a rendering tool out of the box.

It uses LCS, Edit distance and Kuhn–Munkres to diff arrays.

Here's an universal example with set in set and value changes in some set

from jycm.helper import make_ignore_order_func
from jycm.jycm import YouchamaJsonDiffer

left = {
    "set_in_set": [
        {
            "id": 1,
            "label": "label:1",
            "set": [
                1,
                5,
                3
            ]
        },
        {
            "id": 2,
            "label": "label:2",
            "set": [
                4,
                5,
                6
            ]
        }
    ]
}

right = {
    "set_in_set": [
        {
            "id": 2,
            "label": "label:2",
            "set": [
                6,
                5,
                4
            ]
        },
        {
            "id": 1,
            "label": "label:1111",
            "set": [
                3,
                2,
                1
            ]
        }
    ]
}

ycm = YouchamaJsonDiffer(left, right, ignore_order_func=make_ignore_order_func([
    "^set_in_set$",
    "^set_in_set->\\[\\d+\\]->set$"
]))

ycm.diff()

expected = {
    'list:add': [
        {'left': '__NON_EXIST__', 'right': 2, 'left_path': '', 'right_path': 'set_in_set->[1]->set->[1]'}
    ],
    'list:remove': [
        {'left': 5, 'right': '__NON_EXIST__', 'left_path': 'set_in_set->[0]->set->[1]', 'right_path': ''}
    ],
    'value_changes': [
        {'left': 'label:1', 'right': 'label:1111', 'left_path': 'set_in_set->[0]->label',
         'right_path': 'set_in_set->[1]->label', 'old': 'label:1', 'new': 'label:1111'}
    ]
}

assert ycm.to_dict(no_pairs=True) == expected

you can set no_pairs=False to get the all pairs. Here's a rendered example:

As for the example here, you can use it as:

from jycm.helper import make_ignore_order_func
from jycm.jycm import YouchamaJsonDiffer

left = {
    "data": [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
}

right = {
    "data": [{"x": 3, "y": 4}, {"x": 1, "y": 2}]
}

ycm = YouchamaJsonDiffer(left, right, ignore_order_func=make_ignore_order_func([
    "^data",
]))

ycm.diff()

assert ycm.to_dict(no_pairs=True) == {}

Bonus, you the values are interrupted as coordinates on plain, you can even define a operator to determine whether two points should be matched!(Then comparing their values)

Here's the code:

from typing import Tuple

from jycm.helper import make_ignore_order_func
from jycm.jycm import YouchamaJsonDiffer
from jycm.operator import BaseOperator
import math

left = {
    "data": [
        {"x": 1, "y": 1},
        {"x": 10, "y": 10},
        {"x": 100, "y": 100}
    ]
}

right = {
    "data": [
        {"x": 150, "y": 150},
        {"x": 10, "y": 11},
        {"x": 2, "y": 3}
    ]
}


class L2DistanceOperator(BaseOperator):
    __operator_name__ = "operator:l2distance"
    __event__ = "operator:l2distance"

    def __init__(self, path_regex, distance_threshold):
        super().__init__(path_regex=path_regex)
        self.distance_threshold = distance_threshold

    def diff(self, level: 'TreeLevel', instance, drill: bool) -> Tuple[bool, float]:
        distance = math.sqrt(
            (level.left["x"] - level.right["x"]) ** 2 + (level.left["y"] - level.right["y"]) ** 2
        )
        info = {
            "distance": distance,
            "distance_threshold": self.distance_threshold,
            "pass": distance < self.distance_threshold
        }

        if not drill:
            instance.report(self.__event__, level, info)
            return False, 1 if info["pass"] else 0
        return True, 1 if info["pass"] else 0


ycm = YouchamaJsonDiffer(left, right, ignore_order_func=make_ignore_order_func([
    "^data$",
]), custom_operators=[
    L2DistanceOperator("^data->\\[.*\\]$", 10),
])

ycm.diff()

expected = {
    'just4vis:pairs': [
        {'left': 1, 'right': 2, 'left_path': 'data->[0]->x', 'right_path': 'data->[2]->x'},
        {'left': {'x': 1, 'y': 1}, 'right': {'x': 2, 'y': 3}, 'left_path': 'data->[0]',
         'right_path': 'data->[2]'},
        {'left': 1, 'right': 3, 'left_path': 'data->[0]->y', 'right_path': 'data->[2]->y'},
        {'left': {'x': 1, 'y': 1}, 'right': {'x': 2, 'y': 3}, 'left_path': 'data->[0]',
         'right_path': 'data->[2]'},
        {'left': {'x': 1, 'y': 1}, 'right': {'x': 2, 'y': 3}, 'left_path': 'data->[0]',
         'right_path': 'data->[2]'}
    ],
    'list:add': [
        {'left': '__NON_EXIST__', 'right': {'x': 150, 'y': 150}, 'left_path': '', 'right_path': 'data->[0]'}
    ],
    'list:remove': [
        {'left': {'x': 100, 'y': 100}, 'right': '__NON_EXIST__', 'left_path': 'data->[2]', 'right_path': ''}
    ],
    'operator:l2distance': [
        {'left': {'x': 1, 'y': 1}, 'right': {'x': 2, 'y': 3}, 'left_path': 'data->[0]',
         'right_path': 'data->[2]', 'distance': 2.23606797749979, 'distance_threshold': 10,
         'pass': True},
        {'left': {'x': 10, 'y': 10}, 'right': {'x': 10, 'y': 11}, 'left_path': 'data->[1]',
         'right_path': 'data->[1]', 'distance': 1.0, 'distance_threshold': 10,
         'pass': True}
    ],
    'value_changes': [
        {'left': 1, 'right': 2, 'left_path': 'data->[0]->x', 'right_path': 'data->[2]->x', 'old': 1, 'new': 2},
        {'left': 1, 'right': 3, 'left_path': 'data->[0]->y', 'right_path': 'data->[2]->y', 'old': 1, 'new': 3},
        {'left': 10, 'right': 11, 'left_path': 'data->[1]->y', 'right_path': 'data->[1]->y', 'old': 10, 'new': 11}
    ]
}
assert ycm.to_dict() == expected

As you can see jycm report addition and remove for points {'x': 150, 'y': 150} and {'x': 100, 'y': 100} for their distances are too far (more than 10) and value-change for the other two points.

P.S. RENDERER DEMO

🌐
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 - ignore_order=True ensures that the order of items in lists or dictionaries won't affect the comparison result, making it more suitable for JSON comparisons. ... The diff variable now contains the differences between the two JSON objects.
🌐
Quora
quora.com › How-do-you-compare-JSON-objects-regardless-of-order-in-Python
How to compare JSON objects regardless of order in Python - Quora
Answer: first step - load the json ... simple values- i.e. not lists), then you can simply compare them - comparisons of dictionaries ignores ordering. If ......
🌐
PyPI
pypi.org › project › custom-json-diff
custom-json-diff · PyPI
(e.g. timestamps), variable ordering, or other fields which need to be excluded or undergo specialized comparison for one reason or another. Enter custom-json-diff, which allows you to specify fields to ignore in the comparison and sorts all ...
      » pip install custom-json-diff
    
Published   Mar 12, 2025
Version   2.1.6
Find elsewhere
🌐
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 ... very difficult if we don’t know how nested the json is. But, we don’t really have to worry of writing code and all, This is where deepdiff comes in handy. Deepdiff is a powerful python library to compare 2 dictionaries. What makes it powerful is that, during the comparison, deepdiff does not consider the order in which the ...
🌐
Zepworks
zepworks.com › deepdiff › current › ignore_order.html
Ignore Order — DeepDiff 8.6.1 documentation
However, There are often times when you don’t care about the order in which the items have appeared. In such cases DeepDiff needs to do way more work in order to find the differences. There are a couple of parameters provided to you to have full control over. List difference with ignore_order=False which is the default:
🌐
GitHub
github.com › xlwings › jsondiff
GitHub - xlwings/jsondiff: Diff JSON and JSON-like structures in Python · GitHub
>>> diff({'a': [0, {'b': 4}, 1]}, {'a': [0, {'b': 5}, 1]}) {'a': {1: {'b': 5}}} # You can exclude some jsonpaths from the diff (doesn't work if the value types are different) >>> diff({'a': 1, 'b': {'b1': 20, 'b2': 21}, 'c': 3}, {'a': 1, 'b': {'b1': 22, 'b2': 23}, 'c': 30}, exclude_paths=['b.b1', 'c']) {'b': {'b2': 23}} # ...but similarity is taken into account >>> diff({'a': [0, {'b': 4}, 1]}, {'a': [0, {'c': 5}, 1]}) {'a': {insert: [(1, {'c': 5})], delete: [1]}} # Support for various diff syntaxes >>> diff({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, syntax='explicit') {insert: {'c': 4}, update: {'b'
Author   xlwings
🌐
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 😂
🌐
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
Author   rugleb
🌐
PyPI
pypi.org › project › jsondiff
jsondiff · PyPI
>>> diff({'a': [0, {'b': 4}, 1]}, {'a': [0, {'b': 5}, 1]}) {'a': {1: {'b': 5}}} # You can exclude some jsonpaths from the diff (doesn't work if the value types are different) >>> diff({'a': 1, 'b': {'b1': 20, 'b2': 21}, 'c': 3}, {'a': 1, 'b': {'b1': 22, 'b2': 23}, 'c': 30}, exclude_paths=['b.b1', 'c']) {'b': {'b2': 23}} # ...but similarity is taken into account >>> diff({'a': [0, {'b': 4}, 1]}, {'a': [0, {'c': 5}, 1]}) {'a': {insert: [(1, {'c': 5})], delete: [1]}} # Support for various diff syntaxes >>> diff({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, syntax='explicit') {insert: {'c': 4}, update: {'b'
      » pip install jsondiff
    
Published   Aug 29, 2024
Version   2.2.1
🌐
DEV Community
dev.to › keploy › diff-json-a-complete-guide-to-comparing-json-data-3e31
Diff JSON – A Complete Guide to Comparing JSON Data - DEV Community
October 15, 2024 - JSON Diff Best Practices To ensure reliable JSON comparison, follow these best practices: • Ignore Order When Possible: If order doesn’t matter, avoid strict array comparison to prevent unnecessary mismatches.
🌐
CodeRivers
coderivers.org › blog › jsondiff-python
Unveiling the Power of `jsondiff` in Python: Comparing and Analyzing JSON Data - CodeRivers
April 24, 2025 - This tells jsondiff to compare the lists without considering the order of the elements. The output will show that the two lists contain the same elements, even though their order is different. We can also ignore certain fields during the comparison by using the exclude_paths option.
🌐
Readthedocs
deepdiff.readthedocs.io
DeepDiff OLD 4.0.7 documentation! — DeepDiff 4.0.7 documentation
>>> from deepdiff import DeepDiff ... ... Sometimes you don’t care about the order of objects when comparing them. In those cases, you can set ignore_order=True....
🌐
PyPI
pypi.org › project › json-diff
json-diff · PyPI
Add option -a to ignore appended keys (for comparing changing piglit tests). Fix formatted output to stdout (or file). Added test for -i functionality. ... Two small nits in __main__ part.
      » pip install json-diff
    
Published   Aug 25, 2019
Version   1.5.0