Reputation: 191
I'm attempting to parse Json using Groovy's jsonslurper. I'd like to drill down into the "id" and "label" elements and create a key:value pair from them. This is my attempt:
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(myjson)
result = [:]
json.each {
result.put(json.menu.items.id,json.menu.items.label)
}
println result
What I expect is a result of:
[ [Open, null], [OpenNew, Open New], [Zoomin, Zoom In], etc....]
What I get is one list of the id's and one list of the labels. Any suggestion on how to get the desired result? Here is the Json I'm feeding...
{
"menu":{
"header":"SVG Viewer",
"items":[
{
"id":"Open"
},
{
"id":"OpenNew",
"label":"Open New"
},
null,
{
"id":"ZoomIn",
"label":"Zoom In"
},
{
"id":"ZoomOut",
"label":"Zoom Out"
},
{
"id":"OriginalView",
"label":"Original View"
},
null,
{
"id":"Quality"
},
{
"id":"Pause"
},
{
"id":"Mute"
},
null,
{
"id":"Find",
"label":"Find..."
},
{
"id":"FindAgain",
"label":"Find Again"
},
{
"id":"Copy"
},
{
"id":"CopyAgain",
"label":"Copy Again"
},
{
"id":"CopySVG",
"label":"Copy SVG"
},
{
"id":"ViewSVG",
"label":"View SVG"
},
{
"id":"ViewSource",
"label":"View Source"
},
{
"id":"SaveAs",
"label":"Save As"
},
null,
{
"id":"Help"
},
{
"id":"About",
"label":"About Adobe CVG Viewer..."
}
]
}
}
Upvotes: 0
Views: 563
Reputation: 171154
You can do this
def result = new JsonSlurper()
.parseText(json)
.menu
.items
.findAll() // Throw away the 4 `null` ones
.collect { [ it.id, it.label ] }
Upvotes: 2