Forum Discussion

Jseban's avatar
Jseban
Occasional Contributor
8 years ago

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?

 

 

  • Jseban,

     

    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

  • nmrao's avatar
    nmrao
    Champion Level 3
    Sure, the values can be extracted. But can't be stored into property as this is complex object and property can hold simple string.

    It would be helpful if you could tell how you are going to use that data? assertion of values or comparing with someother data?
    • Jseban's avatar
      Jseban
      Occasional Contributor

      What I am trying to do is 

       

      if (condition to check if property array is present in the response)
      context.testCase.testSteps["Properties"].setPropertyValue("Make", jsonSlurper.Types.Vehicle[0].value.Cars[0].value.Properties[0].Make)


      else
      context.testCase.testSteps["Properties"].setPropertyValue("Make", "NA")

      • nmrao's avatar
        nmrao
        Champion Level 3
        You put the code to earlier statement.

        What I was asking was that how this value going to be used? Otherwise no need to store in the property, right?