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

Vladimir picture Vladimir · Nov 11, 2011 · Viewed 14.7k times · Source

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.

Answer

kecso picture kecso · May 7, 2015

Use JSONAssert

They have a loose assert.

Loose:

JSONAssert.assertEquals(exp, act, false);

Strict:

JSONAssert.assertEquals(exp, act, true);