Groovy:如何使用key的值搜索json并在groovy中找到它的子项

lrl1mhuk  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(115)
[
{
    "createTime": "2014-05-12 04:51:46.513343",
    "powered": false,
    "description": "s",
    "current": false,
    "children": [
        {
            "createTime": "2014-05-13 03:50:43.050442",
            "powered": false,
            "description": "Snapshot description",
            "current": false,
            "children": [
                {
                    "createTime": "2014-05-13 03:57:08.209319",
                    "powered": false,
                    "description": "s",
                    "current": false,
                    "children": [
                        {
                            "createTime": "2014-05-13 04:27:00.646064",
                            "powered": false,
                            "description": "s",
                            "current": false,
                            "label": "snap3"
                        },
                        {
                            "createTime": "2014-05-13 21:00:16.374178",
                            "powered": false,
                            "description": "sd",
                            "current": false,
                            "label": "sddsds"
                        }
                    ],
                    "label": "snap2"
                }
            ],
            "label": "snapshot-name5"
        },
        {
            "createTime": "2014-05-14 00:49:33.415858",
            "powered": false,
            "description": "a",
            "current": false,
            "children": [
                {
                    "createTime": "2014-05-14 02:35:10.076829",
                    "powered": false,
                    "description": "sdfsdfsdf",
                    "current": true,
                    "label": "ssfsdf"
                }
            ],
            "label": "assa"
        }
    ],
    "label": "snap1"
}
]

这里我有标签'snap2'作为输入,我需要得到它的孩子的标签(snap3,sddsds)作为输出..我如何在groovy中做到这一点?我搜索了很多东西,但我无法找到一个解决方案..
如果我能从你们任何人那里得到建议就太好了。

fdx2calv

fdx2calv1#

假设你的json在一个String jsonTxt中,你可以做:

def json = ​new groovy.json.JsonSlurper().parseText( jsonTxt )

def recursiveChildrenScan( map, key, value ) {
    if( !map ) { null }
    else if( map[ key ] == value ) { map.children }
    else { map.children.findResult { recursiveChildrenScan( it, key, value ) } }
}

println json.findResult { recursiveChildrenScan( it, 'label', 'snap2' ) }​?.label​
edqdpe6u

edqdpe6u2#

find_recursive(new groovy.json.JsonSlurper().parseText(your_json_here))

def find_recursive(a) {
    a.collect {(it.label == "snap2") ? it.children.collect {it.label} : find_recursive(it.children) }.flatten()
}

相关问题