0

I am trying to fetch all the values from a json whose key name is "label" and want to store in a list. My problem is, the position of label key is not fixed.Sometimes it comes under parent node sometimes in child and sometime under child to child.We can use recursive closure in groovy but i don't know how?

Json::

[
  {
    {
        "id": "2",
        "label": "NameWhatever"
    },
    {
        "id": "123",
        "name": "Some Parent Element",
        "children": [{
                "id": "123123",
                "label": "NameWhatever"
            },
            {
                "id": "123123123",
                "name": "Element with Additional Children",
                "children": [{
                        "id": "123123123",
                        "label": "WhateverChildName"
                    },
                    {
                        "id": "12112",
                        "name": "Element with Additional Children",
                        "children": [{
                                "id": "123123123",
                                "label": "WhateverChildName"
                            },
                            {
                                "id": "12112",
                                "name": "Element with Additional Children",
                                "children": [{
                                        "id": "12318123",
                                        "label": "WhateverChildName"
                                    },
                                    {
                                        "id": "12112",
                                        "label": "NameToMap"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
Kalpa Gunarathna
  • 1,047
  • 11
  • 17
ABhadauria
  • 59
  • 8

1 Answers1

1

Based on similar question

import groovy.json.JsonSlurper

def mapOrCollection (def it) {
    it instanceof Map || it instanceof Collection
}

def findDeep(def tree, String key, def collector) {
    switch (tree) {
        case Map: return tree.each { k, v ->
            mapOrCollection(v)
            ? findDeep(v, key, collector)
                : k == key
                ? collector.add(v)
                    : null
        }
        case Collection: return tree.each { e ->
            mapOrCollection(e)
                ? findDeep(e, key, collector)
                : null
        }
        default: return null
    }
}

def collector = []
def found = findDeep(new JsonSlurper().parseText(json), 'label', collector)
println collector

Assuming variable json contains the given json input from question, prints:

[NameWhatever, NameWhatever, WhateverChildName, WhateverChildName, WhateverChildName, NameToMap]
tkruse
  • 10,222
  • 7
  • 53
  • 80