我有以下json。如何创建以name
为key
和id
为value
的动态映射。并删除key
中具有模式(〜/([0-9])$ /)的任何内容,例如(2)
或(3)
MyCode:
transitionsobj = jiraGetIssueTransitions(idOrKey: Jira_id)
echo prettyPrint(toJson(transitionsobj.data)) \\This prints the below json
def fruitsMap = [:].withDefault{[]}
transitionsobj.each {
fruitsMap.put(transitionsobj.data.fruits.name, transitionsobj.data.fruits.id)
}
println "fruitsMap: ${fruitsMap}"
println(fruitsMap.keySet());
println(fruitsMap.values());
println "Id of Banana is: ${fruitsMap['Banana']}"
JSON文件:
{
"expand":"fruits",
"fruits":[
{
"id":"131",
"name":"Apple (2)",
"to":{
"description":"",
"name":"Apple",
"id":"13895"
}
},
{
"id":"151",
"name":"Mango",
"to":{
"description":"",
"name":"Mango",
"id":"13896"
}
},
{
"id":"161",
"name":"Banana",
"to":{
"description":"",
"name":"Banana",
"id":"10700"
}
}
]
}
当前输出
fruitsMap: [[Apple (2), Mango, Banana]:[131, 151, 161]]
[Apple (2), Mango, Banana]
[131, 151, 161]
Id of Banana is: []
所需的输出:
fruitsMap: [
Apple : 131
Mango : 151
Banana : 161
]
[Apple, Mango, Banana]
[131, 151, 161]
Id of Banana is: 161
我想代替
def fruitsMap = [:].withDefault{[]}
transitionsobj.each {
fruitsMap.put(transitionsobj.data.fruits.name, transitionsobj.data.fruits.id)
}
您只需要:
def fruitsMap = transitionsobj.data.fruits.collectEntries {
[it.name.replaceAll(/(?:\s+).*/, ''), it.id]
}