Categories
Python Answers

How to compare two JSON objects with the same elements in a different order equal with Python?

Spread the love

To compare two JSON objects with the same elements in a different order equal with Python, we can load the JSON strings into dicts with json.loads.

Then we can sort the items with sorted and then compare them.

For instance, we write

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"}
    ]
}
""")

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

is_same = ordered(a) == ordered(b)

to load the JSON strings into dicts with json.loads.

And then we create the ordered function to sort the key-value pairs with the dict keys ordered.

Then we call ordered on both dicts and then check if they’re equal.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *