Jmeter : How to extract first element from json array - jmeter

I am trying to extract first element from a json array. Below mentioned is json array
[
{
"cohortDefinition": {
"Key": 1151,
"id": 1798,
"srcId": "3526",
"pcKey": -1,
"userName": "CHROME_USER",
"name": "JMeter2017-01-06-1483749546167",
"Type": "SUBJECT",
"tool": "CB",
"count": 32757,
"extractionStatus": "",
"dateCreated": "2017-05-10T17:48:45Z"
},
"datasource": {
"id": 2,
"name": "health",
"subjectCount": 116352
},
"project": {
"id": 747,
"name": "Jmeter Project"
}
},
{
"cohortDefinition": {
"Key": 1150,
"id": 1796,
"srcId": "3525",
"pcKey": -1,
"userName": "CHROME_USER",
"name": "JMeter2016-10-27-1477620919644",
"Type": "SUBJECT",
"tool": "CB",
"count": 32757,
"extractionStatus": "",
"dateCreated": "2017-05-10T16:57:11Z"
},
"datasource": {
"id": 2,
"name": "health",
"subjectCount": 116352
},
"project": {
"id": 747,
"name": "Jmeter Project"
}
}
]
From above json i would like to extract first value ie. srcId": "3526".
I tried doing following expression in Jmeter extractor
$..cohortDefinition.srcId[1]
However it is not working. If anyone know how to do this please do let me know.

After JMeter 3.0, you can use JSON Extractor, see:
https://stackoverflow.com/a/47043204/460802
Before JMeter 3.0:
Please follow the below steps to retrieve srcId.
Add a JSON Path Extractor to your request and configure below values.
Destination Variable Name - myVar
JSON Path Expression - $..cohortDefinition.srcId - this will extract all the srcIDs from the JSON.
Default Value - Not Found or Err
Add a Debug Sampler and View Results Tree to your test plan.
Save it and execute.
In Debug Sampler, you can view all the srcId as shown below.
You can now use myVar_1 and myVar_2 in your test plan
using ${myVar_1} ${myVar_2}

No need for Plugin, JMeter has a JSON Extractor that will provide this feature:
Notice:
JSON Path Expression is: $..cohortDefinition.srcId
Match No : 1

Related

How to compare JSON data against DB data in JMeter

I want to compare JSON response with DB data in JMeter. Below is Db table structure (Oracle database):
Table Structure
Below is the JSON
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson#reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
},
{
"id": 8,
"email": "lindsay.ferguson#reqres.in",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-image.jpg"
},
{
"id": 9,
"email": "tobias.funke#reqres.in",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-image.jpg"
},
{
"id": 10,
"email": "byron.fields#reqres.in",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "george.edwards#reqres.in",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "rachel.howell#reqres.in",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
Below is the configuration I have made in JMeter
JDBC Request
JSON Extractor
Response Assertion
But I am getting null response:
Assertion Result
what mistake am I making?
I want to compare each cell data with JSON data. For example ID=7 with JSON and ID=9 with JSON and so on.
Is this possible to do this with any scripting language in JMeter, if yes please suggest the code for the same.
There are multiple problems with your setup:
You need to change your SQL query to SELECT ID from HHDIXI.Data, otherwise you will get LAST_NAME entries in the ID variable
You need to change your JSONPath query to $..data[*].id and set "Match No" to -1 otherwise you will get only first ID into idfromAPI variable
Use Debug Sampler and View Results Tree listener combination to see what variables are being generated by the HTTP and JDBC request samplers.
If you want to compare each ID from API to each ID from the DB in one shot the only option is JSR223 Assertion
Example code:
1.upto(vars.get('ID_#') as int, { index ->
def expected = vars.get('ID_' + index)
def actual = vars.get('idfromAPI_' + index)
if (expected != actual) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Data mismatch, in the database: ' + expected + ', in the API: ' + actual)
}
})
and demo:

Extracting only relevant item from json blob in jmeter

I am quite new on JSR223 which I have been trying out. I have a use case when an item which are available=true only I want to grab id and ignoring out of stock item from below JSON blob. Can someone please advise?
"items": {
"104": {
"id": "104",
"stock": {
"available": true,
"lowOnStock": false,
"quantity": 11
},
},
"105": {
"id": "105",
"stock": {
"available": false,
"lowOnStock": true,
"quantity": 0
},
}
Thanks in advance.
It's recommended to avoid scripting where possible so you can go for JSON Extractor and the following JSONPath query:
$..[?(#.stock.available==true)].id
Demo:
More information: JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios

Jmeter-Regular expression extraction-how to get the value of attribute name

I have the below response from Rest service. I need do capture the value of dSecurityGroup which is "TEST" and pass it to next request. Can yu help on this
"GenericResponse": {
"Service": {
"IdcService": "CHECKIN_UNIVERSAL",
"Document": {
"Field": [
{
"name": "xIPM_APP_1_9:isSetDefault",
"value": "1"
},
{
"name": "IdcService",
"value": "CHECKIN_UNIVERSAL"
},
{
"name": "dSecurityGroup",
"value": "TEST"
},
{
"name": "xIPM_APP_1_6:rule",
"value": "IpmApp_1_Fields_Hide"
},
{
"name": "dpTriggerField",
"value": "xIdcProfile"
},
]
}
}
}
Your JSON response is invalid. check with https://jsonformatter.curiousconcept.com/ and update the correct JSON
Your response is JSON therefore it doesn't make sense to use Regular Expression Extractor.
Consider using JSON Extractor instead, it allows using JsonPath queries which provide handy way to extract the "interesting" values from JSON responses.
In your case the relevant query would be something like:
$..[?(#.name == 'dSecurityGroup')].value
Demo:
More information: API Testing With JMeter and the JSON Extractor

How to extract multiple json values from a Json response

I am trying to extract multiple values from a JSON response on my jmeter script. Below is sample of my response:
{
"startDate": "2018-12-10T15:36:34.400+0000",
"userId": "7211111-2fa90",
"createdBy": "TEST",
"note": {
"content": "Application Submitted "
},
"Type": "SUBMITTED"
},
"currentEventState": "CLOSED",
{
"Xxxx": "test",
"Loc": null,
"Zipcode": [],
"Locality": 82,
"Address": {
"Add": 12302,
"Add2": "place",
"Zip": {
"Phone": "home",
"Email": "test#test.com"
}
},
"state": "MD",
"Cost": "E "
},
"AppID": "cd8d98e6-c2a79",
"Status": "CLOSED",
}
I am trying to extract userid and AppID for the case if the TYPE is Submitted and Status is Closed.I tried using the Json extractor with $.[?(#.Type=="SUBMITTED")].[*].?(#.Status=="CLOSED").userid,APPID, but couldn't get the expected result. Could anyone guide me on this.
You need to use an inline predicate to combine 2 clausees and a semicolon in order to store results into 2 separate JMeter Variables.
Add JSON Extractor as a child of the request which returns above JSON
Configure it as follows:
Names of created variables: userid;appid
JSON Path Expressions: $..[?(#.Type=='SUBMITTED' && #.Status == 'CLOSED')].userId; $..[?(#.Type=='SUBMITTED' && #.Status == 'CLOSED')].AppID
Default values: NA;NA
Here is the demo of single expression working fine:
And here are extracted values reported by the Debug Sampler:

How to simulate multiple child elements with different values in the same Jmeter POST request body?

The below request being the base request,
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
]
I want to simulate this with multiple (1000) 'child' sections like the below in a single JMeter request:
It should create 1000 data set(name,description,unitname,ID,val) with unique values and then post the request. Instead of manually creating multiple tags, can i automate it or create a script to generate this automatically ?
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
{
"name": "Test3",
"description": "testing",
"unitname": simple4,
"ID": 23,
"val": "item"
}
{
"name": "Test4",
"description": "testing",
"unitname": simple6,
"ID": 23,
"val": "item"
}
]
Any help please?
Add JSR223 PreProcessor as a child of your request where you need to send the generated JSON
Put the following code into "Script" area:
import groovy.json.JsonBuilder
import groovy.json.internal.LazyMap
import org.apache.commons.lang3.RandomStringUtils
def data = new ArrayList()
1.upto(1000, {
def entry = new LazyMap()
entry.put('name', 'test' + it)
entry.put('description', RandomStringUtils.randomAlphabetic(10))
entry.put('unitname', 'simple')
entry.put('ID', it)
entry.put('val', 'item')
data.add(entry)
})
def builder = new JsonBuilder()
builder(
data.collect {
[
name : it.get('name'),
descrtiption: it.get('description'),
unitname : it.get('unitname'),
ID : it.get('ID'),
val : it.get('val')
]
}
)
sampler.setPostBodyRaw(true)
sampler.addNonEncodedArgument("", builder.toPrettyString(), "")
Tick Cache compiled script if available box
Make sure groovy is selected in "Language" dropdown
That's it, the above script will generate a JSON Array and set it as the HTTP Request sampler's body.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Resources