Groovy:我如何使用键的值搜索 json 并在 groovy 中找到它的孩子 [英] Groovy : how do i search json with key's value and find its children in groovy
本文介绍了Groovy:我如何使用键的值搜索 json 并在 groovy 中找到它的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里我将标签snap2"作为输入,我需要将其子标签(snap3、sddsds)作为输出..我如何在 groovy 中做到这一点?我搜索了很多东西,但我找不到解决方案..
如果我能得到你们任何人的建议就好了.
解决方案
假设你的 json 是一个 String jsonTxt
,你可以这样做:
def json = new groovy.json.JsonSlurper().parseText( jsonTxt)def recursiveChildrenScan(地图,键,值){如果(!地图){空}else if( map[ key ] == value ) { map.children }else { map.children.findResult { recursiveChildrenScan( it, key, value ) } }}println json.findResult { recursiveChildrenScan( it, 'label', 'snap2' ) } ?.label
[
{
"createTime": "2014-05-12 04:51:46.513343",
"powered": false,
"description": "s",
"current": false,
"children": [
{
"createTime": "2014-05-13 03:50:43.050442",
"powered": false,
"description": "Snapshot description",
"current": false,
"children": [
{
"createTime": "2014-05-13 03:57:08.209319",
"powered": false,
"description": "s",
"current": false,
"children": [
{
"createTime": "2014-05-13 04:27:00.646064",
"powered": false,
"description": "s",
"current": false,
"label": "snap3"
},
{
"createTime": "2014-05-13 21:00:16.374178",
"powered": false,
"description": "sd",
"current": false,
"label": "sddsds"
}
],
"label": "snap2"
}
],
"label": "snapshot-name5"
},
{
"createTime": "2014-05-14 00:49:33.415858",
"powered": false,
"description": "a",
"current": false,
"children": [
{
"createTime": "2014-05-14 02:35:10.076829",
"powered": false,
"description": "sdfsdfsdf",
"current": true,
"label": "ssfsdf"
}
],
"label": "assa"
}
],
"label": "snap1"
}
]
Here I have the label 'snap2' as input and I need to get its children's labels (snap3, sddsds) as output.. How do I do it in groovy? I searched a lot of stuff, but I'm not able to find a solution..
It would be great if I could get a sugggestion from any of you.
解决方案
Assuming your json is in a String jsonTxt
, you can do:
def json = new groovy.json.JsonSlurper().parseText( jsonTxt )
def recursiveChildrenScan( map, key, value ) {
if( !map ) { null }
else if( map[ key ] == value ) { map.children }
else { map.children.findResult { recursiveChildrenScan( it, key, value ) } }
}
println json.findResult { recursiveChildrenScan( it, 'label', 'snap2' ) }?.label
这篇关于Groovy:我如何使用键的值搜索 json 并在 groovy 中找到它的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文