groovy - 使用 json 映射到具有特定键的列表
问题描述
我已经设法得到一个 json 列表并从 json 中得到一个密钥。
我正在研究如何将每个版本值放在一个列表中。我如何从地图上做到这一点?
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)
//If you have the nodes then fetch the first one only
if(convertedJSONMap."items"){
println "Version : " + convertedJSONMap."items"[0]."version"
}
所以我需要的是某种 foreach 循环,它会抛出 Map 并获取项目。每个版本并将其放入列表中。如何?
解决方案
GroovyCollection.collect(closure)
可用于将一种类型的值列表转换为新值列表。考虑以下示例:
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items.collect { it.version }
println list.inspect()
输出:
['1.23', '1.14.0', '2.11', '8.0', '2.32', '4.11.2.3']
Groovy 还提供了扩展运算符*.
,可以将此示例简化为:
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items*.version
println list.inspect()
甚至这个(你可以*.version
用 just替换.version
):
import groovy.json.JsonSlurper
def json = '''{
"items": [
{"id": "ID-001", "version": "1.23", "name": "Something"},
{"id": "ID-002", "version": "1.14.0", "name": "Foo Bar"},
{"id": "ID-003", "version": "2.11", "name": "Something else"},
{"id": "ID-004", "version": "8.0", "name": "ABC"},
{"id": "ID-005", "version": "2.32", "name": "Empty"},
{"id": "ID-006", "version": "4.11.2.3", "name": "Null"}
]
}'''
def convertedJSONMap = new JsonSlurper().parseText(json)
def list = convertedJSONMap.items.version
println list.inspect()
所有示例都产生相同的输出。
推荐阅读
- java - 用于以自定义格式提取嵌套函数的 Java 正则表达式
- c++ - 在 std::map 的 range-for 中的结构化绑定声明中按值获取内置类型
- html - 在移动设备上并排显示图像
- django - Django 因未提供身份验证凭据而失败
- scala - 无法在 Postgres 中实例化外部 Hive Metastore/在类路径中找不到驱动程序
- single-sign-on - Salesforce Commerce Cloud 能否用作外部应用程序的 IDP
- ios - 将 Firebase 数据库快速保存到数组中
- java - 使用 Java 8 Streams 在 Java 中转换地图 - 根据地图的值分离地图
- java - oracle adf 11g EL 比较 partialTrigger 没有正确评估?
- anaconda - conda env 导出是否使用 pip?