使用json映射到具有特定键的列表

时间:2018-11-15 08:24:59

标签: groovy

我设法找到了一个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并仅获取物品。版本,然后将其放在列表中。怎么样?

1 个答案:

答案 0 :(得分:1)

Groovy具有Collection.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还提供了spread operator *.,可以将本示例简化为以下形式:

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来代替.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()

所有示例均产生相同的输出。