Parse an array from the response message using JMeter - jmeter

I am a beginner with Jmeter tool.
I use JMeter to hit a URL and obtained a response message in JSON format.
I want to parse the response to extract every array element and use it to append to the tail of another URL. Can you please tell me how to do this?
example: { "reply": { "code": "111", "status": "SUCCESS", "customer": [ "222-a", "b-333", "44-4", "s-555", "666", "777", "88-8" ] } }

You can use a Regular Expression Extractor (as child of your URL sampler) to first extract the array of values:
Reference name: ary
Regular Expression: \[([^\]]+)\]
Template: $1$
Match No: 1
then use another Regular Expression Extractor to extract the values:
Apply To JMeter variable: ary
Reference name: vals
Regular Expression: "([^"]+)"
Template: $1$
Match No: -1
The match no -1 creates variables vals_1 .. vals_7, which you can then use in a ForEach Controller to assign to a JMeter variable:
Input variable prefix: vals
Output variable name: id
[v] Add '_' before number?
now you can use the JMeter variable ${id} in a nested URL sampler to pass the customer id in a URL.

Related

How to extract value from serialized json response in Jmeter

I am getting a response in form of serialized json format for an api request as below
{"Data":"{\"orderId\":null,\"Tokens\":{\"Key\":\"abcdefgh123456\",\"Txnid\":\"test_5950\"}","success":true,"Test":"success"}
I want to extract Key value in Jmeter and I have to use into next request. Can someone help me on extracting the value?
Your JSON seems incorrect. The valid JSON should be like:
{
"Data":{
"orderId":null,
"Tokens":{
"Key":"abcdefgh123456",
"Txnid":"test_5950"
},
"success":true,
"Test":"success"
}
}
Add a JSON Extractor to the request from where you want to extract the Key value.
assign a variable name, i.e key
JSON Path Expression will be : .Data.Tokens.Key
use the extracted value as ${key} into the next request.
If your JSON really looks exactly like you posted the most suitable Post-Processor would be Regular Expression Extractor
The relevant regular expression would be something like:
"Key"?\s*:?\s*"(\w+)"
where:
``?\s*` - arbitrary number of whitespaces (just in case)
\w - matches "word" character (alphanumeric plus underscores)
+ - repetition
() - grouping
More information:
Using RegEx (Regular Expression Extractor) with JMeter
Perl 5 Regex Cheat sheet
JMeter: Regular Expressions

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.
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:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
You can use JSON Extractor or JSON JMESPath Extractor to extract all the ids from the response.
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)
You can access the list with vars.getObject("lstIds")
List of strings could be seen in the view result tree.
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)

Saving matched values in JMeter postprocessors

In just starting to use JMeter I am trying to set variables of the form taskId_1, taskId_2, taskId_3 (defined in "User Defined Variables") and use them in HTTP Samples (REST requests). When I run postprocessors none of my JSON Extractors or Regular Expression Extractors save the values matched (and I tested the extracted regular expression using RegExp tester.)
The response sent from the GET request that I am parsing looks like (edited for readability):
{
"case-data": {
"Description": "100 parallel tasks",
"Workflow": {
"com.MyCompany": {
"workflow-case-id": null,
"stages": [
{
"stage-guid": "470D2E00-A9E1-11EB-887B-4226FC2CA371",
"tasks": [
{
"task-name": "Stage1Task1P",
"user-group-id": "Joe",
"task-id" : 52
},
{
"task-name": "Stage1Task2P",
"user-group-id": "Joe",
"task-id" : 73
},
{
"task-name": "Stage1Task3P",
"user-group-id": "Joe",
"task-id" : 123
}
]
} ] }}}}
Following the BlazeMeter tutorials, for the Regular Expression Extractor I use
Apply To "Main sample and sub-samples"
Field to check "Response Message"
Name of created variable taskId
Regular expression task-id"\ :\ (.\d+)$
$1$
(I have also tried taskId_1 - my ideal solution would set all the taskId's at once).
For the JSON Extractor that I just tried I use:
Names of created variables: taskId
JSON Path Expressions: $."task-id" (LOG ALL indicates Could not find JSON Path - so I will revise)
Match No: -1
Default Values: taskId not matched
It is as if none of these strings are ever matched so the values are not set - not even default values. I also have a Debug Sample, Debug Postprocessor and a View Results Tree included in the parent Logic Controller - but see no values of variables set anywhere (even in the logs).
I have other JSON extractors that attempt to traverse down the object tree from the top but they also are not setting my User Variables although LOG ALL indicates they are setting the variables of the same name.
What is wrong with my match expressions and assignment parameters?
How can I change my usage of Debug Sampler/Postprocessor/View Result Tree/Properties and variable viewer (which has JMeter variables = True) to observe variables?
Is there a way to run a test plan one step at a time (e.g., a preprocessor, a request, a postprocessor then another postprocessor) by clicking on UI elements?
Regular Expression Extractor:
"task-id"\s*:\s*(\d+)
More information: JMeter Regular Expressions
JSON Extractor:
$..task-id
More information: Jayway JsonPath
To view generated variables just add a Debug Sampler somewhere at the bottom of your script and add View Results Tree listener so Debug Sampler would be in its scope, see How to Debug your Apache JMeter Script for more details.

How to extract variables by using JMeter Extractor

i'am using jmeter "Regular Expression Extractor",my response looks as below
[{"#class":"com.test.dto.BoardDTO",
"ReadOnly":false,
"author":"John",
"id":"89BC331D723F",
"isPublic":false
},
{"#class":"com.test.dto.BoardDTO",
"ReadOnly":false,
"author":"Alex",
"id":"FTH7JBDRF567",
"Public":false
}]
I need to extract all IDs of class:"com.test.dto.BoardDTO" in this case "89BC331D723F" and "FTH7JBDRF567"
Any proposition please !
You should use JSON Extractor instead of regular expression extractor
Add a JSON Extractor and fill in the fields as below
JSON path expression: $.[*][?(#.#class == "com.test.dto.BoardDTO")].id
Match Numbers: -1
This will return all IDs where #class value was com.test.dto.BoardDTO. You can validate it using View Results Tree & Debug Sampler combination.

How to access nested array values in JSON response and use them in a loop in next service in JMeter

I am working on a POST service that give JSON response.
I have to extract certain value from the JSON response. example-
`{
"Result":
{ "Id":22
"StartTime":
"EndTime":
"RoutePoints":
[{ "Id":675,
}
{ "Id":676,
}
]
}
} `
My first part of the question-
How do I refer the "Id" variable inside the "RoutePoint" array using regular expression extractor? I can simply use "Id", but I also have an "Id" variable outside the "RoutePoint" array.
Secondly-
How do I take the "Id" each time and run them in a loop in the following service? Example- I take "Id=675" and perform a job, then take "Id=676" and perform that same job. Please be as detailed as possible, I am new to JMeter.
I would recommend going for JSON Path PostProcessor which is available since JMeter 3.0
Add JSON Path PostProcessor as a child of the request which returns above JSON and configure it as follows:
Variable Names: anything meaningful, i.e. Id
JSON Path Expressions: $..RoutePoints.*.Id
Match Numbers: -1
You should get variables like:
Id_1=675
Id_2=676
Id_matchNr=2
suitable for iteration with i.e. ForEach Controller
Demo:
References:
JSONPath - XPath for JSON
Advanced Usage of the JSON Path Extractor in JMeter

Resources