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.
This answer describes a solution for the problem using the DeltaJSON REST API. DeltaJSON is a commercial product that provides the API either as a service (SaaS) or via a REST server that can be run locally:
arrayAlignment
property set toorderless
.The sample code below shows how to invoke the API with this property setting:
Explanation:
The DeltaJSON Rest API response is an annotated form of the JSON inputs. Extra
dx_
prefixed properties are added to describe the changes. A metadatadx_deltaJSON
property is also included in the JSON.The value of the
dx_deltaJSON
property is an object that has adx_data_sets
property that we can test to see (in a two-way comparison) that the value isA=B
.Here is the result where there are slightly different inputs to that in the question. Here, as well as the order of the array items being changed, 'Mike' has been changed to 'Mikey':