Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two jsons ignoring order of elements in array properties?

I need to compare two strings which represent json objects. For testing purposes I need a way to compare these strings ignoring not only the child elements order (which is quite common) but order of elements in array properties of jsons. I.e.:

group: {
    id: 123,
    users: [
       {id: 234, name: John},
       {id: 345, name: Mike}
    ]
}

should be equal to:

group: {
    id: 123,
    users: [
       {id: 345, name: Mike},
       {id: 234, name: John}
    ]
}

Ideally I need some javascript lib, but other approaches welcome too.

like image 563
Vladimir Avatar asked Nov 11 '11 19:11

Vladimir


People also ask

How do I compare two Jsonobjects?

Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.

How do you compare two JSON responses in Python?

Use json. dumps() and the equal-to operator to compare JSON objects regardless of order. Call json. dumps(json_object, sort_keys) with sort_keys set to True on each json_object to return the object with its key-value pairs sorted in ascending order by the keys.


1 Answers

Use JSONAssert

They have a loose assert.

Loose:

JSONAssert.assertEquals(exp, act, false);

Strict:

JSONAssert.assertEquals(exp, act, true);
like image 128
kecso Avatar answered Sep 19 '22 06:09

kecso