我有一个数组作为源。我想通过使用Groovy将源转换为结果。 我没有看到任何类似的问题。这就是为什么我在这里发布。
我试图获得该家族中的第一个成员,并使用此代码将所有其他成员放入一个subList中,但失败了
source.each{ family -> family.each{
member -> member.get(0).collate(1,family.size()-1)
}
}
来源:
[
[{
"id": "0001",
"role": "parent",
"age": 30
},
{
"id": "0002",
"role": "child",
"age": 1
},
{
"id": "0003",
"role": "child",
"age": 3
}
],
[{
"id": "0004",
"role": "parent",
"age": 31
},
{
"id": "0005",
"role": "child",
"age": 5
}
]
]
结果:
[{
"id": "0001",
"role": "parent",
"age": 30,
"children": [{
"id": "0002",
"role": "child",
"age": 1
},
{
"id": "0003",
"role": "child",
"age": 3
}
]
},
{
"id": "0004",
"role": "parent",
"age": 31,
"children": [{
"id": "0005",
"role": "child",
"age": 5
}]
}]
答案 0 :(得分:1)
您可以通过在“父”地图上添加仅包含子地图的新地图来成形数据(groovy中的+
会合并)。例如:
def data = new groovy.json.JsonSlurper().parseText('[[{ "id": "0001", "role": "parent", "age": 30 }, { "id": "0002", "role": "child", "age": 1 }, { "id": "0003", "role": "child", "age": 3 } ], [{ "id": "0004", "role": "parent", "age": 31 }, { "id": "0005", "role": "child", "age": 5 }]]')
println(data.collect{ groups ->
// XXX
groups.find{ it.role=="parent" } + [children: groups.findAll{it.role=="child"}]
})
// => [[id:0001, role:parent, age:30, children:[[id:0002, role:child, age:1], [id:0003, role:child, age:3]]], [id:0004, role:parent, age:31, children:[[id:0005, role:child, age:5]]]]