Recursively extracting JSON field values in Groovy

后端 未结 1 705
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 09:33

I need to implement a method that will scan a string of JSON for a particular targetField and either return the value of that field (if it exists), or nul

相关标签:
1条回答
  • 2020-12-20 10:20

    Given this input string in a variable called json:

    {
        "a":"a",
        "b":{"f":"f", "g":"g"},
        "c":"c",
        "d":"d",
        "e":[{"h":"h"}, {"i":{"j":"j"}}],
    }
    

    This script:

    import groovy.json.JsonSlurper
    
    def mapOrCollection (def it) {
        it instanceof Map || it instanceof Collection
    }
    
    def findDeep(def tree, String key) {
        switch (tree) {
            case Map: return tree.findResult { k, v ->
                mapOrCollection(v)
                    ? findDeep(v, key)
                    : k == key
                        ? v
                        : null
            }
            case Collection: return tree.findResult { e ->
                mapOrCollection(e)
                    ? findDeep(e, key)
                    : null
            }
            default: return null
        }
    }
    
    ('a'..'k').each { key ->
        def found = findDeep(new JsonSlurper().parseText(json), key)
        println "${key}: ${found}"
    }
    

    Gives these results:

    a: a
    b: null
    c: c
    d: d
    e: null
    f: f
    g: g
    h: h
    i: null
    j: j
    k: null
    
    0 讨论(0)
提交回复
热议问题