我有以下JSON:
UserInput = input("Enter")
if UserInput == "yes":
print ("good job")
# elif requires a condition to evaluate. It's a shorthand for else if
# you can do e.g. elif UserInput == "no"
elif (condition): # colon goes here
print ("wrong")
else:
return
我想写一个 [
{
"Country": "Norway",
"Dept": "2",
"Hours": "08,00"
},
{
"Country": "Norway",
"Dept": "2",
"Hours": "08,00"
},
{
"Country": "Sweden",
"Dept": "1",
"Hours": "08,00"
},
{
"Country": "Sweden",
"Dept": "2",
"Hours": "08,00"
}
]
国家/地区和部门(如果我添加更多参数)并按以下方式获取工作时间总数:
groupBy
如何在groovy中多次添加 [
{
"Country": "Norway",
"Dept": "2",
"Hours": "16,00"
},
{
"Country": "Sweden",
"Dept": "1",
"Hours": "08,00"
},
{
"Country": "Sweden",
"Dept": "2",
"Hours": "08,00"
}
]
以便实现这一目标?我看到我需要添加一些GroupBY
,但我不确定如何
答案 0 :(得分:2)
我认为这就是你要找的东西,但我不喜欢我在地图上迭代并使用<<
到新列表。
诗;你的变量Hours
是一个字符串,我把它作为数字。
def map = objJson.groupBy({it.Country}, {it.Dept}).collectEntries { k, v ->
[k, v.collect{ [Hours: it.value.Hours.sum(), Dept: it.value.Dept[0], Country: it.value.Country[0]] }]
}
def list = []
map.each(){ k, v ->
v.each{
list << it
}
}
return new JsonBuilder(list).toPrettyString()