json - 使用 Groovy 解析 JSON,其中数组和多个对象没有名称以获取列表
问题描述
groovy 和一般编码的新手。尝试执行以下操作:(我在stackoverflow中查看了许多以前的问答,但我发现的解决方案似乎都不起作用)
我有以下 JSON,我需要从中获取供应商名称的列表/字符串,即输出应该类似于:“供应商 1,供应商 2,供应商 3”
[
{
"id":217564,
"created-at":"2020-01-22T08:59:57+00:00",
"state":"submitted",
"supplier":
{
"name":"supplier 1"
}
},
{
"id":217565,
"created-at":"2020-01-22T09:00:00+00:00",
"state":"submitted",
"supplier":
{
"name":"supplier 2"
}
},
{
"id":217566,
"created-at":"2020-01-22T09:00:48+00:00",
"state":"submitted",
"supplier":
{
"name":"supplier 3"
}
}
]
我使用以下 groovy 脚本打印出列表中的所有供应商名称:
import groovy.json.*;
@CustomScriptAction(
input = ['json_response'],
output = 'suppliers'
)
def CustomScriptAction14()
{
def object = new JsonSlurper().parseText(json_response.toString())
def suppliers = "No suppliers"
if(object != null && !object.isEmpty())
{
for(def i =0; i<object.size();i++)
{
suppliers = RString.of(object[i].'supplier'.name.toString());
}
}
return suppliers
}
我得到了输出:“供应商 3”
问题是这个脚本只给了我循环中的最后一个供应商,而不是遍历整个循环并打印出所有供应商。所以我尝试了一个不同的脚本:
import groovy.json.*;
@CustomScriptAction(
input = ['json_response'],
output = 'suppliers'
)
def CustomScriptAction14()
{
def object = new JsonSlurper().parseText(json_response)
def suppliers = object.findAll { it.value instanceof List }
.values()
.flatten()
.collect { [it.'supplier'.'name'] }
}
return suppliers
但有了这个,我得到了一个空白的回应。
我究竟做错了什么?
解决方案
好吧,这最终起作用了:
import groovy.json.*;
@CustomScriptAction(
input = ['json_response'],
output = 'suppliers'
)
def customScript()
{
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(json_response.toString())
suppliers = RString.of(object.'supplier'.'name'.toString())
}
推荐阅读
- javascript - Javascript 我想删除一个元素
- javascript - 提交按钮在其属性更改时不发布
- c++ - 创建一个不是从基类继承的新函数
- laravel - 为什么它在我的模型中作为未定义属性给出错误?
- react-native - 消息:[警告]动画:未指定“useNativeDriver”。这是必需选项
- https - Gatsbyjs 本地 HTTPS 获取浏览器安全错误
- python - 如何在图表中添加过滤器
- apache - 为什么我的服务器的referer总是为空?
- php - Laravel API 从速率限制中排除 1 个 IP 地址
- huawei-mobile-services - 华为手机推送有时候延迟太长,有什么解决办法吗?