When I send a request to an api end point, the following json is coming in my response.
{
"entities": {
"practitioners": {
"f1d26a4b-c489-493d-bccf-7b9c8b92ecac": {
"fullAvatarUrl": null,
"id": "f1d26a4b-c489-493d-bccf-7b9c8b92ecac",
"accountId": "ef757dba-f0d5-4464-a338-4a810e02bf47",
"pmsId": "1",
"type": "Dentist",
"isActive": true,
"isHidden": false
},
"ee87642d-c9a6-4a9d-b99a-a96501f27a7b": {
"fullAvatarUrl": null,
"id": "ee87642d-c9a6-4a9d-b99a-a96501f27a7b",
"accountId": "ef757dba-f0d5-4464-a338-4a810e02bf47",
"pmsId": "2",
"type": "Hygienist",
"isActive": true,
"isHidden": false
},
"d0aeb9eb-f267-45ad-8cdf-eada1155c274": {
"fullAvatarUrl": null,
"id": "d0aeb9eb-f267-45ad-8cdf-eada1155c274",
"accountId": "ef757dba-f0d5-4464-a338-4a810e02bf47",
"pmsId": "3",
"type": "Dentist",
"isActive": true,
"isHidden": false
},
"2f641e8e-c5d6-4fdf-8fbe-f99fe837f441": {
"fullAvatarUrl": null,
"id": "2f641e8e-c5d6-4fdf-8fbe-f99fe837f441",
"accountId": "ef757dba-f0d5-4464-a338-4a810e02bf47",
"pmsId": "4",
"type": "Hygienist",
"isActive": true,
"isHidden": false
}
}
},
"result": [
"f1d26a4b-c489-493d-bccf-7b9c8b92ecac",
"ee87642d-c9a6-4a9d-b99a-a96501f27a7b",
"d0aeb9eb-f267-45ad-8cdf-eada1155c274",
"2f641e8e-c5d6-4fdf-8fbe-f99fe837f441"
]
}
problem statement: I want to select any one from the above 4 random value(want to select the practitioners id and which are sitting at the first element under practitioners) with a validation that isActive should be true and isHidden should be false.
I have tried using the JSON extractor using the expression $.entities.practitioners and match number 0
But it is not selecting the any one rather it select all.
Add JSR223 PostProcessor as a child of the request which returns this JSON
Put the following code into "Script" area:
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def ids = []
json.entities.practitioners.each { practitioner ->
if (practitioner.value.isActive && !practitioner.value.isHidden) {
ids.add(practitioner.key)
}
}
def randomId = ids.get(org.apache.commons.lang3.RandomUtils.nextInt(0, ids.size()))
vars.put('randomId', randomId)
That's it, you should be able to access the random ID as ${randomId} where required.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
I guess this approach can help you,
add a JSR223 PostProcessor to your http request and after that please add the following groovy script to the PostProcessor
Note: this is only to select the random PractitionersId for the validation just use the similar logic.
import groovy.json.*
def response = prev.responseDataAsString ;
def json = new JsonSlurper().parseText(response) ;
def sizeResultPractitioners = json.result.size();
Random rnd = new Random()
def randomResultPractitioners = rnd.nextInt(sizeResultPractitioners);
log.info("---------->"+randomResultPractitioners);
log.info("---------->"+json.result[randomResultPractitioners]);
Related
Having array as:
[France, Switzerland, Croatia, Spain, Brondby, Sonderjyske, CFR Cluj, Ujpest FC, Young Boys , Xamax, Bedford Town, Biggleswade Town]
Having JSON fetched from API call as (NOT full JSON provided)
{
"payload": [
{
"id": 104,
"externalId": "e5b93978-0960-4c01-a201-b15c9e6afb49",
"shortName": "FRA",
"name": "France",
"countryCode": "en",
"leagueId": 1,
"logoUrl": "http://www.example.com/logo.png"
},
{
"id": 110,
"externalId": "7f1f76c1-483c-4c14-b5f9-61e58a5d9328",
"shortName": "Swi",
"name": "Switzerland",
"countryCode": "en",
"leagueId": 1,
"logoUrl": "http://www.example.com/logo.png"
},
{
"id": 2189,
"externalId": "8d23300c-85f4-41b4-b0f1-65e5948f2c80",
"shortName": "Cro",
"name": "Croatia",
"countryCode": "en",
"leagueId": 1,
"logoUrl": "http://www.sdfgsdf.com/image.png"
}
],
"errorCode": 0,
"errorTimeStamp": null,
"errorMessage": null,
"hasError": false
}
For every single member of the array, I need to get its ID's.
I know how match for signle member using JSON path
But, how to fetch all the ID's based on the particullar array?
Given that you have this "array" in a JMeter Variable called array you can get all the IDs by adding a JSR223 PostProcessor and using the following Groovy code in the "Script" area:
vars.get('array').replace('[', '').replace(']', '').tokenize(',').each { country ->
def result = new groovy.json.JsonSlurper().parse(prev.getResponseData()).payload.find { entry -> entry.name == country.trim() }
if (result != null) {
log.info('Country: ' + country.trim() + ', id: ' + result.id)
}
}
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
I am using the following payload as post request to one of my test servers, and I want to retrieve the size of the payload, uniquid from the payload. I am using JSR223 post processer for this any help to get these information
Sample Payload:
POST https://test.eventgrid.azure.net/api/events
POST data:
[
{
"subject": "audit",
"id": "6aca5990-713b-47d1-be81-ed228bd81735",
"eventType": "test.audit",
"eventTime": "2020-08-31T05:02:02.462Z",
"data": {
"version": "1.0",
"application": {
"id": "PI0001",
"name": "PLMAS",
"component": {
"id": "PLMAS01",
"name": "SingleFileImporter",
"type": "LogicApp"
}
},
"audit": {
"id": "168999807c4c46af908ce7a455a5e5eb",
"timestamp": "2020-08-31T05:02:02.462Z",
"type": "input",
"entry": "File retrieved, validated and processed successfully",
"message": {
"headers": "J9SGinwTz0SSrEHrBrhMS3wquHlWu",
"payload": "00=SfsDZ0LESTLZ6VpCmIEDT5nqOPqlwUJknCSIQuAIBM8wKj",
"type": "csv",
"protocol": ""
},
"keys": [
{
"name": "file-archive-location",
"value": "Performance Test From Jmeter"
}
]
},
"context": {
"transactionId": "65174971-62d6-44da-9ecd-537b8d636464",
"messageId": "04cb206c-25dd-4385-bed7-42f770c67cb8",
"customerId": "FANSOI",
"studyId": "FANSOI1234"
}
},
"dataVersion": "1.0",
"metadataVersion": "1"
}
]
Is there any default method like sampler.getUrl() to get the request url and sampler.getArguments().getArgument(0).getValue() to get the request body.
This should do what you want:
import java.util.List;
def size = prev.getBodySizeAsLong() + prev.getHeadersSize();
List<String> list = com.jayway.jsonpath.JsonPath.read( prev.getQueryString(), "$..id");
String uniqueId = list.get(0).toString();
log.info("size:{}, uniqueId:{}", size, uniqueId);
You can use the same functions but instead of sampler go for ctx.getCurrentSampler(), something like:
def data = ctx.getCurrentSampler().getArguments().getArgument(0).getValue()
def size = data.length()
def id = new groovy.json.JsonSlurper().parseText(data)[0].id
log.info('Size: ' + size)
log.info('Id: ' + id)
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Top 8 JMeter Java Classes You Should Be Using with Groovy
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:
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
I'm getting a JSON response back from an API, however the response has several key parameters all called 'jacket' with different values. I am able to parse out the first key but I don't get the rest of the values. Here is some of the code, I might be approaching this the wrong way:
parsed_list = JSON.parse(get_response.body)
orig = parsed_list["_links"]["stuff"]["orig"]
serv = parsed_list["_links"]["stuff"]["serv"]
puts orig.first["jacket"]
puts serv.first["jacket"]
=> 123456789
=> 987654321
This is what the JSON response looks like before I parse it out and set it "parsed_list"
"_links": {
"self": {
"href": "url"
},
"stuff": {
"href": "url",
"orig": [
{
"jacket": "123456789",
"Id": "x",
"selected": true,
}
],
"serv": [
{
"jacket": "987654321",
"Id": "xx",
"selected": false,
},
{
"jacket": "0000000001",
"Id": "xx",
"selected": false,
},
{
"jacket": "1111111110",
"Id": "xx",
"selected": false,
}
]
}
}
}
I need to be able to extract all of the "jacket" values.
The data's right there, you just need to get it:
serv.collect do |entry|
entry['jacket']
end