JSONSLURPER - How to check optional array available in response and save value in property?
Hi,
Below is a sample JSON response.
{
"uri": "VehiclesandGadgets",
"Types": {
"Vehicle": [{
"label": "Click to expand",
"value": {
"Cars": [{
"label": "Click to expand",
"value": {
"Properties": [{
"Make": "Honda",
"Model": "Civic",
"Color": "Red"
}],
"Specifications": [{
"Engine": "V6",
"Gear": "Auto",
"Drive": "AWD"
}]
},
"ov": true
}]
},
"ov": true
}],
"Gadget": [{
"label": "Click to expand",
"value": {
"Gaming": [{
"label": "Click to expand",
"value": {
"Properties": [{
"Type": "Xbox",
"Model": "One",
"Color": "Black"
}]
},
"ov": true
}]
},
"ov": true
}]
},
"isFavorite": false
}
In this JSON, the Vehicle and Gadget are optional arrays. It can be present in the response or not. Similarly Cars, Properties and Specifications are optional.
I want to extract the value of Make using Jsonslurper. But it is possible that properties may not be available in response and some times vehicle may not be. So in such case i want to save Make as "NA"
How can I put a if check for the existence of these optional arrays?
Ok, thank you for the details and patience.
You can use below :
//Pass json string to below parseText method def jsonRes = new groovy.json.JsonSlurper().parseText(json) //Get the make def makes = jsonRes.Types?.Vehicle?.value?.Cars?.value?.Properties?.Make //Assign actual data, otherwise assign NA def result = makes ? makes.flatten()[0] : 'NA' log.info result //You can proceed using result variable do the stuff you needed to do.
Also you can quickly try it online demo