我有一个json文件,其中包含按城市分组的联系信息。我想解析json并创建一个名称和数字列表,但是摆弄一个小时左右后,我无法将其以常规方式使用。
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob@boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice@boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie@chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise@chicago.com"
}
]
}'''
我已经尝试了以下主题的一些变体,但到目前为止都失败了。
parsedjson = slurper.parseText(json)
phonelist = []
parsedjson.each{phonelist.add([it['name'],it['phone']])}
答案 0 :(得分:1)
使用json时比较棘手,因为您需要查找列表中的值...您可以使用findAll
来做到这一点,所以给定json:
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob@boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice@boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie@chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise@chicago.com"
}
]
}'''
您可以像当前一样导入JsonSlurper并解析json:
import groovy.json.JsonSlurper
def parsedjson = new JsonSlurper().parseText(json)
然后;
def result = parsedjson.findAll { it.value instanceof List } // Find all entries with a list value
.values() // Get all the lists
.flatten() // Merge them into a single list
.collect { [it.name, it.phone] } // grab the name and phone for each