首页 > 解决方案 > 我是否需要一个 for 循环才能使用 Groovy JsonSlurper 在 json 中查找键/值?

问题描述

python for循环:

actions = json_data['actions']
for a in actions:
    if 'causes' in a:
        for cause in a['causes']:
            if 'userId' in cause:
                self.user = cause['userId']

我如何在 groovy 中做到这一点?

def jenkins_data = new JsonSlurper().parseText(obj)

使用这个 json,我不确定如何深入获取 userId。我想我需要使用 for 循环来检查列表中的每个元素的“原因”键,然后重复“用户 ID”键。

这是我正在处理的示例有效负载。

self.payload_a = {"number": 3585, "url": "https://test.m.test.com/job/gfdsgdsf/3585/",
                  "displayName": "master_3585", "timestamp": 1516992464686,
                  "actions": [{"something": "nothing"}, {"causes": [{"userId": "build"}]}]}

使用示例有效负载,我可以回显 jenkins_data.actions.cause 并查看输出,但是回显 jenkins_data.actions.causes.userId 为空(即使 userId 肯定在有效负载中)

当我跑

echo jenkins_data.actions.causes

我明白了

[null, [[_TestIdCause, shortDescription:Started by user, B, userId:valueweneed, userName:test, B]], null, null, null, null, null, null, null, null, null, null, null, null, null, null]

标签: jsongroovy

解决方案


答案是肯定的。您需要放置一个循环来遍历json中的所有节点。

解析 json 非常复杂。

根据 Json :遍历时可以从 ('userId') 之类的同一节点返回任何数据类型。如下图

"userId" : "A"
...
"userId" : { ... }
...
"userId" : [ ... ]

您需要根据需要处理此返回数据。当您在问题中询问获取userId节点时,只需使用如下所示的 xpath

def json = new JsonSlurper().parseText(jsontxt)

println json.actions.causes.userId

在您的情况下,它返回列表。就这样flatten吧。

println json.actions.causes.userId.flatten()

推荐阅读