Groovy:将json中的值添加到地图中

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

我有以下json。如何创建以namekeyidvalue的动态映射。并删除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
json parsing groovy maps
1个回答
0
投票

我想代替

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]
}
© www.soinside.com 2019 - 2024. All rights reserved.