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

python compare two json objects and get difference
python compare json keys
compare json files using python
compare json objects javascript
c# compare two json objects and get differences
json diff
jquery compare two json objects
how to compare two json objects in angular 6

How can I test whether two JSON objects are equal in python, disregarding the order of lists?

For example ...

JSON document a:

{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}

JSON document b:

{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}

a and b should compare equal, even though the order of the "errors" lists are different.

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

Python Comparing Two Json objects irrespective of the sequence of , are python lists' with elements in different orders in two json objects. assuming you have json1 and json2 loaded with the json entries Logically those are identical. I don't know of any tools that will ignore order for you. Compare Two Nested JSON Objects As we saw earlier, JsonParser can parse the tree-like structure of JSON. Each JsonObject and JsonArray contain other JsonElement objects, which can, themselves be of type JsonObject or JsonArray .

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.

How to detect differences between two json string in node.js , How do I compare two JSON objects in Node JS? Objects also compare well in that each member property is identified by a string which should be unique within the object (it does not have to be unique but behaviour is unpredictable if they are not unique!). Therefore corresponding members can be identified without ambiguity even if the order of the members is different.

Decode them and compare them as mgilson comment.

Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)

>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

But order is important in list; sorting will solve the problem for the lists.

>>> [1, 2] == [2, 1]
False
>>> [1, 2] == sorted([2, 1])
True

>>> a = '{"errors": [{"error": "invalid", "field": "email"}, {"error": "required", "field": "name"}], "success": false}'
>>> b = '{"errors": [{"error": "required", "field": "name"}, {"error": "invalid", "field": "email"}], "success": false}'
>>> a, b = json.loads(a), json.loads(b)
>>> a['errors'].sort()
>>> b['errors'].sort()
>>> a == b
True

Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.

How to compare two JSON objects with their key-value pairs using , and return a value based on the arguments passed. But the problem is Fluent assertion fails only when the attribute count/names are not matching. If the json values are different it passes. I require to fail when values are different. InstanceObjActual.Should().BeEquivalentTo(InstanceObjExpected); For example I have the actual and expected json to compare as below.

For the following two dicts 'dictWithListsInValue' and 'reorderedDictWithReorderedListsInValue' which are simply reordered versions of each other

dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(sorted(a.items()) == sorted(b.items()))  # gives false

gave me wrong result i.e. false .

So I created my own cutstom ObjectComparator like this:

def my_list_cmp(list1, list2):
    if (list1.__len__() != list2.__len__()):
        return False

    for l in list1:
        found = False
        for m in list2:
            res = my_obj_cmp(l, m)
            if (res):
                found = True
                break

        if (not found):
            return False

    return True


def my_obj_cmp(obj1, obj2):
    if isinstance(obj1, list):
        if (not isinstance(obj2, list)):
            return False
        return my_list_cmp(obj1, obj2)
    elif (isinstance(obj1, dict)):
        if (not isinstance(obj2, dict)):
            return False
        exp = set(obj2.keys()) == set(obj1.keys())
        if (not exp):
            # print(obj1.keys(), obj2.keys())
            return False
        for k in obj1.keys():
            val1 = obj1.get(k)
            val2 = obj2.get(k)
            if isinstance(val1, list):
                if (not my_list_cmp(val1, val2)):
                    return False
            elif isinstance(val1, dict):
                if (not my_obj_cmp(val1, val2)):
                    return False
            else:
                if val2 != val1:
                    return False
    else:
        return obj1 == obj2

    return True


dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(my_obj_cmp(a, b))  # gives true

which gave me the correct expected output!

Logic is pretty simple:

If the objects are of type 'list' then compare each item of the first list with the items of the second list until found , and if the item is not found after going through the second list , then 'found' would be = false. 'found' value is returned

Else if the objects to be compared are of type 'dict' then compare the values present for all the respective keys in both the objects. (Recursive comparison is performed)

Else simply call obj1 == obj2 . It by default works fine for the object of strings and numbers and for those eq() is defined appropriately .

(Note that the algorithm can further be improved by removing the items found in object2, so that the next item of object1 would not compare itself with the items already found in the object2)

Python Compare Two Lists, How to compare two JSON objects with the same elements in a different order equal? How can I test whether two JSON objects are equal in python, disregarding  Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects. In the following example, objects were stringified() at first and then compared with each other. Example. Live Demo

How to compare two JSON objects with the same elements in a , Learn how to use Jackson to compare two JSON objects using the built-in comparator I just announced the new Learn Spring course, focused on the and s2 is not the same, the equals() method ignores the order and treats them as equal. As we can see, the JSON contains a nested element contact. There are two cases where deepEqual is faster than a JSON comparison. if the two objects are referentially equal jsonEqual will still generate the two complete JSON strings. deepEqual on the other hand will immediately see that the two options are the same and finish 8000 times more quickly.

Compare Two JSON Objects with Jackson, If you convert the dict_keys objects to lists and compare them, it will compare the ordering. print(d1 == d2) # True; dict comparison. print(d1.keys() == d2.keys()) # True; dictkeys comparison. print(list(d1.keys()) == list(d2.keys())) # False; list comparison. List elements have a specific order for a reason. – ATOzTOA Apr 7 '17 at 20:55. As noted in this answer, a JSON array is sorted so these objects containing arrays with different sort orders wouldn't be equal in the strict sense.

How to compare two JSON files in Python, Checking if two JSON objects are equal regardless of order compares the pairs of each object and returns True if the objects contain the exact same elements. If there is a mapping, it uses the mapped property name instead. This means, for example, that if it comes across a property in the JSON object named code, it will use the property name errorCode instead. Then it finds the property on the C# class which has a JsonProperty attribute with that name.

How to compare JSON objects regardless of order in Python, Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties. Created by  It will return false for two equal json having different order of elements. – deadpool May 5 '16 at 12:43 @deadpool the principle is sound, you'd just need to change the comparison to be more involved (checking for key fields for example rather than a simple equals of the trees). – jwenting Apr 20 '17 at 10:46

Comments
  • Duplicate of stackoverflow.com/questions/11141644/…
  • Why not just decode them and compare? Or do you mean the the order of the "Array" or list elements doesn't matter either?
  • @user2085282 That question has a different problem going on.
  • Please forgive my naivety, but why? List elements have a specific order for a reason.
  • As noted in this answer, a JSON array is sorted so these objects containing arrays with different sort orders wouldn't be equal in the strict sense. stackoverflow.com/a/7214312/18891
  • thank you so much Zero Piraeus. it's exactly the general soolution that I need. but the only problem is that code works only for python 2.x not for python3. I get the following error : TypeError: unorderable types: dict() < dict() Anyway solution is now clear. I will try to make it work for python3. Thanks a lot
  • @HoussamHsm I meant to fix this to work with Python 3.x when you first mentioned the unorderable dicts problem, but somehow it got away from me. It now works in both 2.x and 3.x :-)
  • when there's an list like ['astr', {'adict': 'something'}], I got TypeError when trying to sort them.
  • @Blairg23 you've misunderstood the question, which is about comparing JSON objects as equal when they contain lists whose elements are the same, but in a different order, not about any supposed order of dictionaries.
  • @Blairg23 I agree that the question could be more clearly written (although if you look at the edit history, it's better than it started out). Re: dictionaries and order – yes, I know ;-)