将Groovy Json解析为键值

时间:2018-12-07 04:16:43

标签: json groovy

我正在尝试使用Groovy的jsonslurper解析Json。我想深入研究“ id”和“ label”元素,并从中创建一个key:value对。这是我的尝试:

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
​

我期望的结果是:

[[Open,null],[OpenNew,Open New],[Zoomin,Zoom In]等...

我得到的是一个ID列表和一个标签列表。关于如何获得理想结果的任何建议?这是我要喂的杰森...

{  
   "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..."
         }
      ]
   }
}

1 个答案:

答案 0 :(得分:2)

您可以做到

def result = new JsonSlurper()
    .parseText(json)
    .menu
    .items
    .findAll() // Throw away the 4 `null` ones
    .collect { [ it.id, it.label ] }