Forum Discussion

SankarB's avatar
SankarB
Occasional Contributor
8 years ago

How to get the item count

Hi,

 

How do i get the count of items for the below JSON response 

 


{
"@type": "com.a.common.model.dto.CollectionDTO",
"id": null,
"items": [

{
"@type": "com.a.b.client.model.dto.Asset",
"value": "s2",
"Name": "U",
"status": "OK",
"type": "SENSOR",
"Time": 1497360632027,
"deviceType": "SCANNER",
"devicePortType": "GENERAL",
"devicePortIndex": 3,
"deviceStatus": "CONNECTED",
"sensorMapperConfigId": null,
"currentSensorValue": {
"@type": "com.a.common.client.model.dto.SensorValueDTO",
"id": null,
"numericValue": 54.0,
"units": "PERCENT",
"stateValue": null,
"stateLabel": null
},
"units": "PERCENT",
"parent": {
"@type": "com.b.c.d.model.dto.Entity",
"id": "p9",
"label": null,
"status": null,
"type": "POT"
}
},
{
"@type": "com.a.b.client.model.dto.Devices",
"value": "s3",
"Name": "U",
"status": "OK",
"type": "SCANNER",
"Time": 1497360632027,
"deviceType": "SCANNER",
"devicePortType": "GENERAL",
"devicePortIndex": 3,
"deviceStatus": "CONNECTED",
"sensorMapperConfigId": null,
"currentSensorValue": {
"@type": "com.a.common.client.model.dto.SensorValueDTO",
"id": null,
"numericValue": 54.0,
"units": "PERCENT",
"stateValue": null,
"stateLabel": null
},
"units": "PERCENT",
"parent": {
"@type": "com.b.c.d.model.dto.Entity",
"id": "p9",
"label": null,
"status": null,
"type": "POT"
}
}
]
}

  • Add Script Assertion with below code:

     

    assert context.response, "Response is empty or null"
    
    def json = new groovy.json.JsonSlurper().parseText(context.response)
    log.info json.items.size()
    
  • Try replacing [i] with [$i] to reference the value as a number instead of a string. 

  • nmrao's avatar
    nmrao
    Champion Level 3

    Add Script Assertion with below code:

     

    assert context.response, "Response is empty or null"
    
    def json = new groovy.json.JsonSlurper().parseText(context.response)
    log.info json.items.size()
    
    • SankarB's avatar
      SankarB
      Occasional Contributor

      Hi Rao,

       

      Thanks a lot for the help. Its working.

       

      Regards,

      Sankar

    • SankarB's avatar
      SankarB
      Occasional Contributor

      Hi Rao,

       

      I am able to fetch the count. And using for loop when i am iterating it based on the count, and in the loop i am trying to fetch the "deviceType" value for which  it may not exists for few items. 

      I have written "def deviceType = context.expand( '${getAllDevices#Response#$[\'items\'][i][\'deviceType\']}' ) 

       I am getting null value. But if hardcode the value i am getting the actual result.

       

      Could you please help me.

      • groovyguy's avatar
        groovyguy
        Community Hero

        Try replacing [i] with [$i] to reference the value as a number instead of a string.