使用groovy在map下添加新的键和值对

使用groovy在map下添加新的键和值对,groovy,jsonslurper,Groovy,Jsonslurper,我有这个JSON。与key1或key2类似,我希望使用groovy向这个json添加新的密钥对。我正在使用JsonSlurper() def mJson=新文件(MAPPINGJSON).text; def mJsonObject=parser.parseText(mJson); def list=mJsonObject.map; def keyFound=false; 用于(列表中的项目) { if(item.key==templateKey) { def值=item.value; value

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

def mJson=新文件(MAPPINGJSON).text;
def mJsonObject=parser.parseText(mJson);
def list=mJsonObject.map;
def keyFound=false;
用于(列表中的项目)
{
if(item.key==templateKey)
{
def值=item.value;
value.add();
项目价值=价值;
keyfind=true;
打破
}
keyFound=false;
}
如果(!keyFound)
{
println“找不到密钥”;
//如何添加新密钥对?
}

由daggett编写的列表[templateKey]=[]
是一种方法,但您也可以使用一行程序来实现这一技巧

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]=[]
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?
}
def list=  mJsonObject.map;
list.computeIfAbsent(templateKey, { [] }).add(templateValue)