How to set default value if I dont get key/value in groovy

Viewed 44

I have a requirement where I am reading a JSON array and mapping the value:

input:

[
{
    "Name": "1",
    "Partner": "11"
},
{
    "Name": "2"
},
{
    "Name": "3",
    "Partner": "33"
} 
]

as we can see there is no "Partner" key in second object , then now I need to set default as below:

[
{
    "Name": "1",
    "Partner": "11"
},
{
    "Name": "2",
    "Partner": 0
},
{
    "Name": "3",
    "Partner": "33"
}
]
1 Answers

You could do something like this:

String jsonInputString = """
    [{"Name": "1", "Partner": "11" },
     {"Name": "2"},
     {"Name": "3", "Partner": "33" } ]
"""

// parse the JSON into a List of Map
def maps = new JsonSlurper().parseText(jsonInputString)

def resultingMaps = maps.collect { map ->
    if(!map.containsKey('Partner')) {
        // the numbers in the initial map are Strings but
        // the question shows this one as a number, so here
        // it is a number, could just as well be a String with
        // the 0 in it...
        map.Partner = 0
    }
    map
}
    
// resultingMaps will be [[Name:1, Partner:11], [Name:2, Partner:0], [Name:3, Partner:33]]

EDIT:

I am new to groovy, not sure how to proceed, Tried few stuff using "Withdefault" , however no success

withDefault may not be exactly what you want because it won't put the 0 in the Map unless that key is requested. You can see that by running this...

def resultingMaps = maps.collect { map ->
    map.withDefault { key ->
        if(key == 'Partner') {
            return 0
        }
    }
}

// this will makes sure every Map has a "Partner" entry...
resultingMaps*.get('Partner')

// resultingMaps will be [[Name:1, Partner:11], [Name:2, Partner:0], [Name:3, Partner:33]]
Related