Question

[
{
    "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"
}
]

Here I have the label 'snap2' as input and I need to get its children's labels (snap3, sddsds) as output.. How do I do it in groovy? I searched a lot of stuff, but I'm not able to find a solution..

It would be great if I could get a sugggestion from any of you.

Was it helpful?

Solution

Assuming your json is in a String jsonTxt, you can do:

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​

OTHER TIPS

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()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top