在 Groovy 中递归提取 JSON 字段值

Recursively extracting JSON field values in Groovy

我需要实现一种方法,该方法将扫描 JSON 的字符串以查找特定的 targetField 和 return 该字段的值(如果存在),或者 null(如果不是):

// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'fizz') => 'buzz'
// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'foo') => null
String extractFieldValue(String json, String targetField) {
    // ...
}

此解决方案必须是递归的,并且可以在(分层)JSON 字符串中的任何嵌套级别工作。它还需要适用于 JSON 数组。

迄今为止我最好的尝试:

String extractFieldValue(String json, String targetField) {
    def slurper = new JsonSlurper()
    def jsonMap = slurper.parseText(json)

    jsonMap."${targetField}"
}

这仅适用于顶级(非嵌套)JSON 字段。问了Google大神如何递归使用JsonSlurper,没找到有用的。这里有什么想法吗?

在名为 json 的变量中给定此输入字符串:

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

这个脚本:

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

给出这些结果:

a: a
b: null
c: c
d: d
e: null
f: f
g: g
h: h
i: null
j: j
k: null