Reputation: 1314
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??
Upvotes: 0
Views: 2612
Reputation: 50245
Pretty close. Try flatten().
Try jsresult.lvl1.lvl2.lvl3.collect{it.a3}.flatten()
or myTry.flatten()
Upvotes: 1