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
🌐
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()))
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

Python - Compare two JSON with different length and without order - Stack Overflow
I want to compare two json data without order because there are same items with different orders. More on stackoverflow.com
🌐 stackoverflow.com
python - Comparing two JSON objects irrespective of the sequence of elements in them - Stack Overflow
Is there any way / class / module in python to compare two json objects and print the changes/differences? I have tried with "json_tools" which is gives fairly good results, however diff failed in case if there are python lists' with elements in different orders in two json objects. More on stackoverflow.com
🌐 stackoverflow.com
How to compare two json objects ignoring the order of fields
Hello everyone, I’m passing a request body with a JSON object containing n number of fields. The body format is included in the body and this specific JSON object is in the pre-requisite script. Upon hitting the post request an ID gets generated. Now, I use get API with this ID to fetch the ... More on community.postman.com
🌐 community.postman.com
0
0
October 23, 2023
Comparing JSON Files While Excluding Certain Keys
Why not try them? What are you looking for with this question? More on reddit.com
🌐 r/learnpython
3
1
April 7, 2019
🌐
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
It uses a dict_keys type, which preserves the key ordering for printing, but disregards the ordering for comparison. If you convert the dict_keys objects to lists and compare them, it will compare the ... In Python, the == operator is recursive. So if you read in two JSON files, you can compare them like this:
🌐
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.
🌐
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 - Since dictionaries are unordered in Python, this method naturally handles order differences ? import json # JSON objects to compare json_obj1 = '{"name": "John", "age": 30, "city": "New York"}' json_obj2 = '{"age": 30, "city": "New York", "name": "John"}' # Convert JSON objects to dictionaries dict1 = json.loads(json_obj1) dict2 = json.loads(json_obj2) # Compare dictionaries if dict1 == dict2: print("The JSON objects are equal.") else: print("The JSON objects are not equal.") print(f"Dict 1: {dict1}") print(f"Dict 2: {dict2}")
🌐
Medium
medium.com › @abedmaatalla › compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - 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 elements inside the dictionaries are present.
🌐
Community
community.safe.com › home › forums › fme form › transformers › how to compare two json without looking the order of their attribute?
How to compare two json without looking the order of their attribute? | Community
June 30, 2017 - # PythonCaller Script Example [Updated] import json def processFeature(feature): array1 = json.loads(feature.getAttribute('_result1')) array2 = json.loads(feature.getAttribute('_result2')) feature.setAttribute('_same', 'yes' if (array1 == array2) else 'no') updated the script example.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 69497434 › python-compare-two-json-with-different-length-and-without-order
Python - Compare two JSON with different length and without order - Stack Overflow
for form in selectedProductForm: for jsonItem in getJson: if form.id == jsonItem['Id'] and form.isUpdated == False: if jsonItem['Label'] is not None and jsonItem['Label'][0:1].isalnum() == True: form.metaKey = jsonItem['Label'].title() else: form.metaKey = form.metaKey if jsonItem['Input'] is not None and jsonItem['Input'][0:1].isalnum() == True: form.metaVal = jsonItem['Input'].title() form.isUpdated = True form.save() So, there will be only deletable items left because all of added and overwrited items' isUpdate attribute are False. for form in selectedProductForm: if form.isUpdated == False: form.isDeleted = True form.isUpdated = True form.save() After all these operations I make isUpdated=false of all items in order to make update operation again later.
🌐
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.
🌐
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} [...
🌐
sqlpey
sqlpey.com › python › solved-how-to-compare-two-json-objects-for-equality-regardless-of-order
Solved: How to Compare Two JSON Objects for Equality Regardless of Order
November 6, 2024 - import json json_a = {"errors": ... True · Since Python dictionaries are inherently unordered collections, you can directly compare them provided that the lists are sorted before the comparison....
🌐
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%
🌐
pythontutorials
pythontutorials.net › blog › how-to-compare-two-json-objects-with-the-same-elements-in-a-different-order-equal
How to Compare Two JSON Objects with Same Elements (Different Order) as Equal in Python — pythontutorials.net
We’ll explore three methods to compare JSON objects with the same elements but different order: The json module’s dumps function converts Python objects to JSON strings. By setting sort_keys=True, it sorts the keys of all dictionaries in the JSON structure.
🌐
Postman
community.postman.com › help hub
How to compare two json objects ignoring the order of fields - Help Hub - Postman Community
October 23, 2023 - Hello everyone, I’m passing a request body with a JSON object containing n number of fields. The body format is included in the body and this specific JSON object is in the pre-requisite script. Upon hitting the post request an ID gets generated. Now, I use get API with this ID to fetch the ...
🌐
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
🌐
CodeRivers
coderivers.org › blog › python-com-pare-json-objects
Comparing JSON Objects in Python - CodeRivers
March 3, 2025 - This is important because JSON objects are unordered, and without sorting the keys, two equivalent objects might produce different JSON strings. For more complex and in-depth comparisons of JSON objects, especially when dealing with nested structures and data types, the deepdiff library is a great choice. deepdiff can find the differences between two Python objects at a deep level.
🌐
Reddit
reddit.com › r/learnpython › comparing json files while excluding certain keys
r/learnpython on Reddit: Comparing JSON Files While Excluding Certain Keys
April 7, 2019 -

Hi everyone,

We have two JSON files we could like to compare. Problem is, some values are different (like current time and date for example), and we want to exclude those values. There couple of solution I can think about:

  1. Ignore the fact it's a JSON and MASK specific data. So the original file will look like `"time": "1/1/2019"` for example. I will looking for the file using REGEX for `"time"` and change the value to `*MASKED*`. The file I compare to will already have this, so diff will pass successfully. I'm not a fan of this - because Regex and manual masking can get very complex really fast.

  2. I can just turn the JSON into Dict, and remove the keys. This way I can compare only the relevant data.

  3. A third option will be looking for a Python library that does something like that already (I couldn't find myself) that diff json files but allow excludes. Or write my class that compare Dicts and ignore specific keys if they showing up. But this again can get very complex early one with nested Dicts (JSON).

Any ideas?

🌐
Baeldung
baeldung.com › home › json › jackson › compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - Learn how to use Jackson to compare two JSON objects using the built-in comparator and a custom comparator