在Groovy中,我试图过滤Map,据此我特别想检查cars.models.colors
是否为空。如果是这样,我要删除此特定元素。
例如,我希望删除:
{
"name": "m5",
"colors": []
}
代码:
#!/usr/local/bin/groovy
import groovy.json.*
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText '''
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [
{ "colorName": "grey", "colorId": "123" },
{ "colorName": "white", "colorId": "844" },
{ "colorName": "green", "colorId": "901" }
]
}]
}, {
"name": "vw",
"models": [{
"name": "golf",
"colors": [{ "colorName": "black", "colorId": "392" }]
}]
}, {
"name": "bmw",
"models": [{
"name": "m5",
"colors": []
}]
}
]
}
'''
Map filtered = [:]
filtered['root'] = object.cars.models.colors.findAll {it.value.isEmpty()}
println JsonOutput.prettyPrint(JsonOutput.toJson(filtered))
一旦成功应用了过滤,我期望JSON看起来像
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [{
"colorName": "grey",
"colorId": "123"
},
{
"colorName": "white",
"colorId": "844"
},
{
"colorName": "green",
"colorId": "901"
}
]
}]
},
{
"name": "vw",
"models": [{
"name": "golf",
"colors": [{
"colorName": "black",
"colorId": "392"
}]
}]
},
{
"name": "bmw",
"models": []
}
]
}
但是,我的代码当前仅返回:
{
"root": [
[
]
]
}
答案 0 :(得分:1)
由于加载的JSON已经是原始文件的“副本”,因此您可以仅处理加载的object
(直接对其进行操作)。
因此,您可以迭代汽车并过滤掉所有不带颜色的车型。例如
import groovy.json.*
def object = new JsonSlurper().parseText('''
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [
{ "colorName": "grey", "colorId": "123" },
{ "colorName": "white", "colorId": "844" },
{ "colorName": "green", "colorId": "901" }
]
}]
}, {
"name": "bmw",
"models": [{"name": "m5","colors": []}]
}]
}
''')
object.cars.each{
it.models = it.models.findAll{ it.colors }
}
println JsonOutput.prettyPrint(JsonOutput.toJson(object))