Groovy compare two json with unknown nodes names and values
Solution 1
Just compare the slurped maps:
def map1 = new JsonSlurper().parseText(document1)
def map2 = new JsonSlurper().parseText(document2)
assert map1 == map2
Solution 2
Try the JSONassert library: https://github.com/skyscreamer/JSONassert. Then you can use:
JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT)
And you will get nicely formatted deltas like:
java.lang.AssertionError: Resources.DbRdsLiferayInstance.Properties.KmsKeyId
Expected: kms-key-2
got: kms-key
Michał Surdy
Updated on July 18, 2022Comments
-
Michał Surdy almost 2 years
I have a rest API to test and I have to compare two json responses. Below you can find a structure of the file. Both files to compare should contains the same elements but order might be different. Unfortunately the names, the type (simple, array) and the number of keys (root, nodeXYZ) are also not known.
{"root": [{ "node1": "value1", "node2": "value1", "node3": [ { "node311": "value311", "node312": "value312" }, { "node321": "value321", "node322": "value322" } ], "node4": [ { "node411": "value411", "node412": "value413", "node413": [ { "node4131": "value4131", "node4132": "value4131" }], "node414": [] } { "node421": "value421", "node422": "value422", "node423": [ { "node4231": "value4231", "node4232": "value4231" }], "node424": [] }] "node5": [ {"node51": "value51"}, {"node52": "value52"}, ] }]}
I have found some useful information in Groovy - compare two JSON objects (same structure) and return ArrayList containing differences Getting node from Json Response Groovy : how do i search json with key's value and find its children in groovy but I could not combine it to an solution. I thought the solution might look like this:
take root get root children names check if child has children and get their names do it to the lowest leve child
With all names in place comparing should be easy (I guess) Unfortunately I did not manage to get keys under root
-
Michał Surdy over 8 yearsThat does the job, any advice how to extract delta from this comparison ?
-
tim_yates over 8 yearsYou would need to write something that walks maps, and works out where the differences lie...
-
Swami PR almost 8 yearsThe assertion will not work if the Json fields in the respective documents are not in order limiting the usefulness of this approach.
-
Rao over 6 years@tim_yates, simple and nice solution. How about ignoring certain fields such as dates, ids etc while comparison? Is it that one needs to traverse map and do customize comparison? or any simple way?
-
Moses Liao GZ about 3 yearsif the order of the same keys are different between the two maps will it assert it as the same?
-
tim_yates about 3 yearsYes. Give it a go