Groovy 比较两个具有未知节点名称和值的 json [英] Groovy compare two json with unknown nodes names and values

查看:21
本文介绍了Groovy 比较两个具有未知节点名称和值的 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个休息 API 来测试,我必须比较两个 json 响应.您可以在下面找到文件的结构.要比较的两个文件应包含相同的元素,但顺序可能不同.不幸的是,名称、类型(简单、数组)和键的数量(根、节点XYZ)也不知道.

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"},
   ]
}]}

我发现了一些有用的信息Groovy - 比较两个 JSON 对象(结构相同)并返回包含差异的 ArrayList从 Json 响应中获取节点Groovy:我如何使用键的值搜索 json 并在 groovy 中找到它的孩子但我无法将它结合到解决方案中.我认为解决方案可能如下所示:

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

有了所有的名字,比较应该很容易(我猜)不幸的是,我没有设法在 root 下获得密钥

With all names in place comparing should be easy (I guess) Unfortunately I did not manage to get keys under root

推荐答案

只需比较 slurped maps:

Just compare the slurped maps:

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

assert map1 == map2

这篇关于Groovy 比较两个具有未知节点名称和值的 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆