json - 我是否需要一个 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]
解决方案
答案是肯定的。您需要放置一个循环来遍历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()
推荐阅读
- sas - 新 SAS 数据集中的变量排列
- regex - 如何匹配正则表达式 php 中文本的前 20 个单词中的单词?
- vim - vim-airline:如何创建自定义 tabline 格式化程序以使其包含当前目录?
- docker - 为什么 Kafka 会警告“分区有没有匹配侦听器的领导代理”?
- python - 如何将字典元素动态分组到列表中?
- python - 在python中,逐行读取标准的功能性和内存效率是什么?
- python - 欧拉计划 642
- r - 矩阵中的应用函数给出二元运算符错误
- parallel-processing - MPI 零计数数据交换
- haskell - 也许 Monad 的用法