2017-12-18 188 views
0

我想從一個json的關鍵名是「label」並且想要存儲在一個列表中獲取所有的值。 我的問題是,標籤鍵的位置不固定。有時它在子節點下有時在父節點下,有時在子節點下到子節點。我們可以在常規中使用遞歸閉包,但我不知道如何?groovy json中的遞歸閉包

的Json ::

[ 
    { 
    { 
     "id": "2", 
     "label": "NameWhatever" 
    }, 
    { 
     "id": "123", 
     "name": "Some Parent Element", 
     "children": [{ 
       "id": "123123", 
       "label": "NameWhatever" 
      }, 
      { 
       "id": "123123123", 
       "name": "Element with Additional Children", 
       "children": [{ 
         "id": "123123123", 
         "label": "WhateverChildName" 
        }, 
        { 
         "id": "12112", 
         "name": "Element with Additional Children", 
         "children": [{ 
           "id": "123123123", 
           "label": "WhateverChildName" 
          }, 
          { 
           "id": "12112", 
           "name": "Element with Additional Children", 
           "children": [{ 
             "id": "12318123", 
             "label": "WhateverChildName" 
            }, 
            { 
             "id": "12112", 
             "label": "NameToMap" 
            } 
           ] 
          } 
         ] 
        } 
       ] 
      } 
     ] 
    } 
] 

回答

1

基於similar question

import groovy.json.JsonSlurper 

def mapOrCollection (def it) { 
    it instanceof Map || it instanceof Collection 
} 

def findDeep(def tree, String key, def collector) { 
    switch (tree) { 
     case Map: return tree.each { k, v -> 
      mapOrCollection(v) 
      ? findDeep(v, key, collector) 
       : k == key 
       ? collector.add(v) 
        : null 
     } 
     case Collection: return tree.each { e -> 
      mapOrCollection(e) 
       ? findDeep(e, key, collector) 
       : null 
     } 
     default: return null 
    } 
} 

def collector = [] 
def found = findDeep(new JsonSlurper().parseText(json), 'label', collector) 
println collector 

假設變量json含有問題,打印給定的輸入JSON:

[NameWhatever, NameWhatever, WhateverChildName, WhateverChildName, WhateverChildName, NameToMap]