在 Groovy 中递归提取 JSON 字段值 [英] Recursively extracting JSON field values in Groovy

查看:71
本文介绍了在 Groovy 中递归提取 JSON 字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个方法来扫描特定 targetField 的 JSON 字符串,并返回该字段的值(如果存在)或 null(如果没有):

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 null (if it doesn't):

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

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

This solution has to be recursive and work at any nesting-level in the (hierarchical) JSON string. Also it needs to work for JSON arrays as well.

迄今为止我最好的尝试:

My best attempt so far:

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

    jsonMap."${targetField}"
}

这仅适用于顶级(非嵌套)JSON 字段.我问谷歌大神如何递归使用 JsonSlurper ,但找不到任何有用的东西.这里有什么想法吗?

This only works on top-level (non-nested) JSON fields. I asked the Google Gods how to use JsonSlurper recursively, but couldn't find anything useful. Any ideas here?

推荐答案

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

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

这个脚本:

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

这篇关于在 Groovy 中递归提取 JSON 字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆