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.
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.
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.
Use JSONAssert
They have a loose assert.
Loose:
JSONAssert.assertEquals(exp, act, false);
Strict:
JSONAssert.assertEquals(exp, act, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With