born2Learn
born2Learn

Reputation: 1413

Jmeter extracting values from response and sending to other requests

I have a JSON response below:

"books": [
{
   "name" : "test1",
   "id" : "T01"
},
{
   "name" : "test2",
   "id" : "T02"
},
{
   "name" : "test3",
   "id" : "T03"
},
]

I am extracting all respective ids and sending it as a body to another request. Other request takes it as an array of strings but when I am extracting it, it is showing as integers:

Currently it shows:  ids_ALL = [T01, T02, T03]
and I have to pass it like: ids_ALL = ["T01", "T02", "T03"]

Note: I am suffixing _ALL to get all ids.

Since it is not passing the array as string, I am getting an error.

Is there away to extract it and put it in array of strings or way to use post-processer and then convert the array and send to other request.

Upvotes: 0

Views: 1296

Answers (3)

Dmitri T
Dmitri T

Reputation: 168217

This one-liner will extract all the IDs and generate the JSON Array you're looking for:

vars.put('payload', (new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()).books.id.collect()).toPrettyString()))

no other extractors are needed, you can refer the generated array as ${payload} later on where required

In Taurus it can be put into the JSR223 Block

More information:

Upvotes: 2

Janesh Kodikara
Janesh Kodikara

Reputation: 1841

Another quick solution

Add a JSR223 Post Processor below the JSON Extractor to create strings with the available values.

String  booksIds_ALL=vars.get("booksIds_ALL")
def lstIds = "\"" + booksIds_ALL.replace(",", "\",\"") + "\""
vars.putObject("lstIds",lstIds)

enter image description here

enter image description here

Upvotes: 1

Janesh Kodikara
Janesh Kodikara

Reputation: 1841

You can use JSON Extractor or JSON JMESPath Extractor to extract all the ids from the response.

enter image description here

Place a JSR223 Post processor just below the JSON Path Extractor to create a list of Strings (ids)

def idCount=vars.get("booksIds_matchNr").toInteger()
def lstIds=[]

for(i in 1..idCount){
    String currentId=vars.get("booksIds_" + i)
    lstIds.add("\""+ currentId + "\"" )
    //lstIds.add("${currentId}" )
    
}

vars.putObject("lstIds",lstIds)

enter image description here

You can access the list with vars.getObject("lstIds")

List of strings could be seen in the view result tree.

enter image description here

Upvotes: 1

Related Questions