0
{
"map": {
    "key1": [3,12,13,11],
    "key2": [21,23],
    "key3": [31,32,33]
}}

I have this JSON. similar to key1 or key2 I want to add new key- pair to this json using groovy. I am using 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?
}
knowdotnet
  • 839
  • 1
  • 15
  • 29

1 Answers1

0

list[templateKey] = [<some value>]by daggett is one way, but you can also use a one liner to do the trick.

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

It uses a function to provide the default value of the map.

aristotll
  • 8,694
  • 6
  • 33
  • 53