0

Hi is there's a way I can simulate this scenario using JSONPath? Example I have multiple City value and I want all to extract and put it on an Array. Your response is highly appreciated. Thank you so much.

[ { "id": "MAIN", "key": 1 }, { "city": "Roselle", "id": "87", "state": "IL", "key": 1000 }, { "city": "Chicago", "id": "7102", "state": "IL", "key": 110 }, { "city": "Crown Point", "id": "7106", "state": "IN", "key": 110038 } ]

Screenshot:

enter image description here

Expected Output:

enter image description here

Ralph
  • 105
  • 7

3 Answers3

1
  1. Add JSR223 PostProcessor as a child of the request which returns the above JSON

  2. Put the following code into "Script" area:

    vars.put('cities', new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()).findResults{entry -> entry.city}).toPrettyString())
    
  3. Refer generated value as ${cities} where required

Demo:

enter image description here

More information:

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
-1

Here is one solution. You can extract the cities from the JSON response using JSON Extractor or JSON JMESPath Extractor post processors.

enter image description here

Your data will be extracted into a set of variables.

Add a JSR223 Post Processor just below the JSON Path Extractor and assign the cities to an array. You can share the array with other following samplers with vars.put('cities',lstCities)

int cityCount=vars.get("cities_matchNr").toInteger()
def lstCities =[]

for(i in 1..cityCount){
    lstCities.add(vars.get("cities_" + i))
}
vars.putObject("cities", lstCities)

The following will demonstrate using the array from the subsequent JSR223 component.

def lstCities=vars.getObject("cities") as String[]
log.info("Number of cities ${lstCities.size()}")

for(i in 0..<lstCities.size()) {
    log.info("City $i is ${lstCities[i]}")
}

enter image description here

Janesh Kodikara
  • 1,670
  • 1
  • 12
  • 23
-1

Another solution with Groovy

Add a JSR223 Postprocessor to the request and add the following code to extract the cities into an array.

import groovy.json.JsonSlurper

String strResponse=prev.getResponseDataAsString()
log.info("responseJSON ${strResponse}")

def jsonSlurper = new JsonSlurper()
def jsonResponse = jsonSlurper.parseText(strResponse)
def lstCities=jsonResponse.city
lstCities.removeAll([null])

log.info("Cities ${lstCities.size()}")
for(i in 0..<lstCities.size()){
    log.info("City ${i.next()} is ${lstCities[i]} ")
}
Janesh Kodikara
  • 1,670
  • 1
  • 12
  • 23