Groovy compare two json with unknown nodes names and values

假如想象 提交于 2019-11-29 15:08:44

问题


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


回答1:


Just compare the slurped maps:

def map1 = new JsonSlurper().parseText(document1)
def map2 = new JsonSlurper().parseText(document2)

assert map1 == map2



回答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


来源:https://stackoverflow.com/questions/33410830/groovy-compare-two-json-with-unknown-nodes-names-and-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!