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

时间:2019-04-07 14:27:34

标签: json groovy nested collect

使用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}
]

2 个答案:

答案 0 :(得分:3)

您可以解决这个问题,使用collect将通过collectMany方法获得的options的多个列表合并在一起。

请参见以下代码段:

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" ],
]

答案 1 :(得分:0)

感谢朱塞佩! 我已经用一种不太常见的方法解决了这个问题:

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?:''}"/ ]
    })
};