groovy json中的递归闭包

时间:2017-12-18 12:02:02

标签: recursion groovy

我正在尝试从名为“label”的json中获取所有值,并希望存储在列表中。 我的问题是,标签键的位置不固定。有时它在父节点下有时在子节点下,有时在子节点之下。我们可以在groovy中使用递归闭包但我不知道如何?

的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"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:1)

基于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

假设变量json包含来自问题的给定json输入,则打印:

[NameWhatever, NameWhatever, WhateverChildName, WhateverChildName, WhateverChildName, NameToMap]