Groovy收集嵌套元素以及外部元素

问题描述 投票:1回答:1

使用Groovy,要求是收集地图的嵌套元素值及其顶级元素值。

不确定是否需要递归方法。

示例JSON

{
"items": [
      {
      "attribute": "Type",
      "options":       
      [
                  {
            "label": "Type1",
            "value": "1"
         },
                  {
            "label": "Type2",
            "value": "2"
         }

      ]
   },
      {
      "attribute": "Size",
      "options":       [
                  {
            "label": "SizeA",
            "value": "A"
         },
                  {
            "label": "SizeB",
            "value": "B"
         }
      ]
   }
]
}

收集后的预期产量

[
{attribute=Type,label=Type1,value=1},
{attribute=Type,label=Type2,value=2},
{attribute=Size,label=SizeA,value=A},
{attribute=Size,label=SizeB,value=B}
]
json groovy nested collect
1个回答
4
投票

您可以使用options通过collect方法组合多个collectMany列表来解决此问题。

请参阅以下代码段:

def input = """
{
  "items": [
    {
      "attribute": "Type",
      "options": [
         {
           "label": "Type1",
           "value": "1"
         },
         {
           "label": "Type2",
           "value": "2"
         }
      ]
   },
   {
     "attribute": "Size",
     "options": [
         {
            "label": "SizeA",
            "value": "A"
         },
         {
            "label": "SizeB",
            "value": "B"
         }
     ]
  } ]
}"""

def json = new groovy.json.JsonSlurper().parseText(input)

/* collectMany directly flatten the two sublists 
 * [ [ [ type1 ], [ type2 ] ], [ [ sizeA ], [ sizeB ] ] ]
 * into
 * [ [type1], [type2], [sizeA], [sizeB] ]
 */
def result = json.items.collectMany { item ->
    // collect returns a list of N (in this example, N=2) elements 
    // [ [ attribute1: ..., label1: ..., value1: ... ],
    //   [ attribute2: ..., label2: ..., value2: ... ] ]
    item.options.collect { option ->
        // return in [ attribute: ..., label: ..., value: ... ]
        [ attribute: item.attribute ] + option
    }
}

assert result == [
    [ attribute: "Type", label: "Type1", value: "1" ],
    [ attribute: "Type", label: "Type2", value: "2" ],
    [ attribute: "Size", label: "SizeA", value: "A" ],
    [ attribute: "Size", label: "SizeB", value: "B" ],
]

0
投票

感谢Giuseppe!我用一种不太常规的方法解决了这个问题:

def result  = [];//Create new list with top-level element and nested elements
json.items.each {item ->
    result.addAll(item.options.collect{ option ->
        [attribute: /"${item?.attribute?:''}"/, label: /"${option?.label?:''}"/, value: /"${option?.value?:''}"/ ]
    })
};
© www.soinside.com 2019 - 2024. All rights reserved.