一尘不染

Groovy:如何使用Key的值搜索json并在Groovy中找到其子级

json

[
{
    "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中做到这一点?我搜索了很多东西,但找不到解决方案。

如果我能从你们中得到任何建议,那就太好了。


阅读 750

收藏
2020-07-27

共1个答案

一尘不染

假设您的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​
2020-07-27