Groovy 映射:获取列的所有值
Groovy Mapping : Get all the values of a column
我有一个 json,如下所示,我正在尝试使用 Groovy 获取所有“开发”主机的列表。
我怎样才能做到这一点 ?我附上了我目前正在使用的示例代码,但由于显而易见的原因,它不起作用。我是 Groovy.
的新手
{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
代码:
apiResponse = <Code which returns the json as mentioned above>
def parser = new JsonSlurper()
def host_list = parser.parseText(apiResponse)
dev_hosts = host_list[]['dev']
print dev_hosts
预期结果:
['host1','host2','host3','host4']
def dev_hosts = host_list.values().collectMany{it['dev']}
编辑:OP 调整了规格:dev
应该是一个变量和列表
需要展平(大概在第一级)。
有很多方法可以做到这一点,最好的方法可能取决于更多地了解关于顶层 JSON 文档等中有多少对象的常见使用模式,但是以下功能:
String jsonInput = """
{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
}"""
def object = new JsonSlurper().parseText(jsonInput)
def results = object.collect { it.value.dev }.flatten()
assert results == ['host1', 'host2', 'host3', 'host4']
我有一个 json,如下所示,我正在尝试使用 Groovy 获取所有“开发”主机的列表。 我怎样才能做到这一点 ?我附上了我目前正在使用的示例代码,但由于显而易见的原因,它不起作用。我是 Groovy.
的新手{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
代码:
apiResponse = <Code which returns the json as mentioned above>
def parser = new JsonSlurper()
def host_list = parser.parseText(apiResponse)
dev_hosts = host_list[]['dev']
print dev_hosts
预期结果:
['host1','host2','host3','host4']
def dev_hosts = host_list.values().collectMany{it['dev']}
编辑:OP 调整了规格:dev
应该是一个变量和列表
需要展平(大概在第一级)。
有很多方法可以做到这一点,最好的方法可能取决于更多地了解关于顶层 JSON 文档等中有多少对象的常见使用模式,但是以下功能:
String jsonInput = """
{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
}"""
def object = new JsonSlurper().parseText(jsonInput)
def results = object.collect { it.value.dev }.flatten()
assert results == ['host1', 'host2', 'host3', 'host4']