【问题标题】:Add new key and value pair under map using groovy使用 groovy 在 map 下添加新的键值对
【发布时间】:2018-07-21 11:10:02
【问题描述】:
{
"map": {
    "key1": [3,12,13,11],
    "key2": [21,23],
    "key3": [31,32,33]
}}

我有这个 JSON。类似于 key1 或 key2 我想使用 groovy 向这个 json 添加新的密钥对。我正在使用 JsonSlurper()。

def mJson = new File(MAPPINGJSON).text;
def mJsonObject = parser.parseText(mJson);
def list=  mJsonObject.map;
def keyFound= false;
for (item in list)
{
    if (item.key == templateKey)
    {
        def values = item.value;
        values.add(<some value>);
        item.value= values;
        keyFound = true;
        break;
    }
    keyFound = false;
}
if(!keyFound)
{
    println "Key not found";
 //   How to add new key pair?
}

【问题讨论】:

  • list[templateKey] = [&lt;some value&gt;]

标签: groovy jsonslurper


【解决方案1】:

list[templateKey] = [&lt;some value&gt;]by daggett 是一种方法,但您也可以使用 one liner 来解决问题。

def list=  mJsonObject.map;
list.computeIfAbsent(templateKey, { [] }).add(templateValue)

它使用一个函数来提供地图的默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多