在Groovy中递归提取JSON字段值 [英] Recursively extracting JSON field values in Groovy
问题描述
我需要实现一种方法,它将扫描特定的 targetField
的JSON字符串,并返回该字段的值(如果存在)或 null
(如果没有):
//例如:extractFieldValue / {fizz:buzz} /,'fizz')=> 'buzz'
//例如:extractFieldValue(/ {fizz:buzz} /,'foo')=> null
String extractFieldValue(String json,String targetField){
// ...
}
该解决方案必须是递归的,并且可以在(分层)JSON字符串中的任何嵌套级别上工作。
到目前为止我的最佳尝试是:
字符串extractFieldValue(String json,String targetField){
def slurper = new JsonSlurper()
def jsonMap = slurper.parseText(json)
jsonMap。 $ {targetField}
}
这仅适用于顶层(non-嵌套)JSON字段。我问Google Gods如何递归地使用 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 ||它的instanceof Collection
$ b $ def findDeep(def tree,String key){
switch(tree){
case)返回tree.findResult {k,v - >
mapOrCollection(v)
? findDeep(v,key)
:k == key
? v
:null
}
案例集合:return tree.findResult {e - >
mapOrCollection(e)
? findDeep(e,key)
:null
}
default:return null
}
}
('a'..' k')。每个{键 - >
def found = findDeep(new JsonSlurper()。parseText(json),key)
println$ {key}:$ {found}
}
$ c
给出以下结果:
a :a
b:null
c:c
d:d
e:null
f:f
g:g
h:h
i:null
j:j
k: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) {
// ...
}
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}"
}
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?
解决方案 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
这篇关于在Groovy中递归提取JSON字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!