用groovy和jsonslurper收集属性列表到单个列表中 [英] Collect list of attributes with groovy and jsonslurper into single list
本文介绍了用groovy和jsonslurper收集属性列表到单个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从JSON层次中收集属性列表的最佳方法是什么?这是我想要做的:
What's the best way to collect a list of attributes from a JSON hierarchy? Here's what I'm trying to do:
import groovy.json.JsonSlurper
def jsontxt = '''
{
"lvl1": [
{
"lvl2": [
{
"lvl3": [
{
"a1": false,
"a2": {
"a2b1": false,
"a2b2": false
},
"a3": "wantvalue1"
},
{
"a1": false,
"a2": {
"a2b1": false,
"a2b2": false
},
"a3": "wantvalue2"
}
],
},
],
}
]
}
'''
def jsresult = new JsonSlurper().parseText(jsontxt)
def mytry = jsresult.lvl1.lvl2.lvl3.collect{it.a3} // [[[wantvalue1, wantvalue2]]]
assert ["wantvalue1","wantvalue2"] == mytry
抱歉,输入不够干净,但我不想失去我的处境。
Apologies the input is not as clean as it could be but I didn't want to lose my situation.
我想要的是一个没有额外空列表的基本列表。我知道必须有一种非常酷的方式来做到这一点,但我对此并不满意。 。 。帮助??
What I want is a basic list without the additional empty lists. I know there must be a really cool way to do this but I'm not groovy enough for it. . . help??
推荐答案
非常接近。尝试 flatten()。
尝试 jsresult.lvl1.lvl2.lvl3.collect {it.a3} .flatten()
或 myTry.flatten()
这篇关于用groovy和jsonslurper收集属性列表到单个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文