json - 使用 Groovy 从 Json 对象数组中获取 Json 对象
问题描述
我想为下面的 Json 数组获取 prodType ULTRA 的 productLines。我得到了地图数组并使用 findIndexValues 来获取索引,但它不起作用。我错过了什么?我查看了结构不太复杂的类似示例,并且与我正在尝试的示例没有太大区别
这是我的数据:
def static modelData="""
{
"models": [
{
"transactionId": "01-PROD0021",
"prodCode": "ISN-2017WDE",
"product": "VASCULAR DNNT",
"prodType": "SDISCNT",
"productLines": [
{
"productLineId": "ELECT-2221",
"productDescriptor": "XTRA-SONIC DNNP",
"unitPrice": "",
},
{
"productLineId": "ELECT-2223",
"productDescriptor": "HEADPH",
"unitPrice": "1.33",
}
]
},
{
"transactionId": "01-PROD0024",
"prodCode": "ISN-5543XDR",
"product": "ULTRASOUND DEEP SONAR",
"prodType": "ULTRA",
"productLines": [
{
"productLineId": "MEDCN-XTR221",
"productDescriptor": "ELECTRONIC RESPR",
"unitPrice": "2.44",
},
{
"productLineId": "MEDCN-XTR376",
"productDescriptor": "SPNG ELECTRONIC DEFIB",
"unitPrice": "6.22",
}
}
]
]
}
"""
这是我的尝试:
def parsed = new JsonSlurper().parseText(modelData)
// Find index of the prodCode with 'ULTRA'
int [] vals=parsed.data.findIndexValues{
it -> it.key=='prodType' && it.value=='ULTRA'}
//Does not print anything
vals?.each {println "Found an index! ${it}" }
解决方案
代码有几处错误: 1. 循环通过一个“数据”节点,而该节点没有。使用parsed.data
2. 每个节点都是一个类似地图的结构。因此,您检查地图是否包含prodType
具有 value的键ULTRA
。使用it.prodType == 'ULTRA'
.
专业提示: 1. 您可以打印闭包上的数据,以便您更快地找到解决方案。
推荐阅读
- mysql - 将 Yii2 中的变量插入数据库
- c# - 名称空间中不存在名称 xxx DataProvider
- centos7 - CentOS 7 - Payara 5 无法在端口 80 上运行
- python - 随机森林的表现比其他方法好得多
- python - 为字典python中的每个键选择最大值
- r - 是否有用于根据额外列更改部分变量的 dplyr 函数?
- python - 用于多项式除法的 `numpy.polydiv()` 和 `scipy.signal.deconvolve()` 之间的区别
- azure-devops - 如何升级“基本 + 测试计划”的 devops 访问级别的用户许可证?
- javascript - 在 Windows 上仅定位 Google Chrome
- sql - SQL Server 中的填充函数 - 处理多个主键