1

I want to assert the value of a property in Json response with the use of Groovy script in SoapUI. I know a value for name but I need to know on which position the id is.

json response example:

{  
   "names":[  
      {  
         "id":1,
         "name":"Ted"
      },
      {  
         "id":2,
         "name":"Ray"
      },
      {  
         "id":3,
         "name":"Kev"
      }
   ]
}

Let's say I know that there is a name Ray, I want the position and the id (names[1].id)

Rao
  • 20,781
  • 11
  • 57
  • 77
tras
  • 41
  • 1
  • 5

1 Answers1

1

Here is the script to find the same:

import groovy.json.*
//Using the fixed json to explain how you can retrive the data
//Of couse, you can also use dynamic value that you get 
def response = '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}'''
//Parse the json string and get the names
def names = new JsonSlurper().parseText(response).names
//retrive the id value when name is Ray 
def rayId = names.find{it.name == 'Ray'}.id
log.info "Id of Ray is : ${rayId}"

//Another way to get both position and id
names.eachWithIndex { element, index ->
  if (element.name == 'Ray') {
    log.info "Position : $index, And Id is : ${element.id}"
  }
}

You can see here the output

enter image description here

Rao
  • 20,781
  • 11
  • 57
  • 77