过滤Groovy映射

过滤Groovy映射,groovy,Groovy,在Groovy中,我试图过滤一个映射,我特别想检查cars.models.colors是否为空。如果是,我想删除这个特定元素 例如,我希望删除: { "name": "m5", "colors": [] } 代码: 一旦过滤成功应用,我希望JSON看起来像 { "cars": [{ "name": "ford", "models": [{ "name": "fiesta",

在Groovy中,我试图过滤一个映射,我特别想检查
cars.models.colors
是否为空。如果是,我想删除这个特定元素

例如,我希望删除:

{
   "name": "m5",
   "colors": []
}
代码:

一旦过滤成功应用,我希望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": [
        [

        ]
    ]
}

因为加载的JSON已经是原始信号的“副本”,所以只需处理加载的
对象(直接操作它)

所以你可以迭代汽车,过滤掉所有没有颜色的模型。例如

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))

请加上代码,这是不工作的,我有-这是上面我很抱歉,你是对的。代码位于第一个代码块的末尾。我对JSON进行了一些压缩以使其更可见。太棒了!这很有效。此外,如果我现在想删除宝马作为一个元素,现在“图片”是空的呢?谢谢你的帮助@cfrick
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))