Jmeter - How to validate portions of response json - json

I have the following json:
{
"content":
[
{
"id":1,
"userId":2,
"storeId":8,
"userFirstName":"Max",
"userLastName":"Mustermann",
"city":"Berlin",
"spendQuantity":100,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":23,
"id":"432",
"rate":"1.9345345",
"symbol":"USD",
"rank":2,
}
},
{
"id":2,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Berlin",
"spendQuantity":1000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":3,
"id":"234",
"rate":"1.922222245345",
"symbol":"USD",
"rank":2,
}
},
{
"id":3,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Munich",
"spendQuantity":3000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":2332,
"id":"234",
"rate":"3.234234",
"symbol":"USD",
"rank":2,
}
},
{
"id":4,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Essen",
"spendQuantity":4000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":234,
"id":"234",
"rate":"333.234234",
"symbol":"USD",
"rank":2,
}
}
}
But I need to verify it partially - Only the fields in the nested jsons where city is Berlin or Essen, but without the rateObject (I don't need to verify this part). With other words I need to verify nested jsons with ids- 1,2,4 - all fields, without the information in rateObject.

Partial Answer and Suggestion:
We can apply the filter condition in the JSON Query to fetch the matched details.
For Example: To get the id of the mentioned city,
JSON Query:
$.content[?(#.city=="Berlin" || #.city=="Essen")].id
Output:
[
1,
2,
4
]
Similarly, you can assert all the required fields using the filter JSON Query.
JMeter JSON Extractor will provide only one value at a time.So, you can either add some logic to verify all the occurrences or multiple verification can be added by specifying the id index ( $.content[?(#.city=="Berlin" || #.city=="Essen")].id[0] --> It gives the first occurrence Id )
If you want to validate multiple fields,then you can write the customized script in Bean Shell Post Processor.(Refer the below link and you will get some idea)
Extracting JSON Response using Bean Shell Postprocessor
If you are using the Bean Shell Post Processor, then required java jar files should be placed in JMeter ClassPath( Folder: apache-jmeter-4.0\lib\ext)

Related

Trying to get values form a list inside a JSON respons

My goal is to loop over a JSON response, grab two values, and build out an API call to load information into a POST to create a policy I am building.
To start out on this, I am trying to get two values from a JSON response to assign as variables to build the POST call, which will be the second step to this. As each different "id" and "name" key is assigned, I would like to build out a JSON payload and send the POST calls one at a time. The keys "id" and "name" occurs multiple times in the response payload and I am having issues capturing the two keys.
JSON response
data = {
"data":[
{
"id":"02caf2be-3245-4d3d",
"name":"ORA-FIN-ACTG",
"description":"Oracle",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"03af2f46-fad6-41a1",
"name":"NBCMAINFRAME",
"description":"Network",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"0649628b-0e3b-48df",
"name":"CAMS",
"description":"Customer",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"069d4bcf-3e50-4105",
"name":"SHAREPOINTSITES",
"description":"Sharepoint",
"links":{
"web":"https://com/",
"api":"https://com/"
}
}
],
"took":0.013,
"requestId":"1f364470"
}
I have tried various "for loops" to grab the data. Here is one of the loops below:
data = json.loads(data)
data[0]['data'][0]['name']
for item in range(len(data)):
print(data[item]['data'][0]['name'])
I have also tried reading it as a dictionary:
for data_dict in data:
for key, value in data_dict.items():
team.append(key)
id.append(value)
print('name = ', team)
print('id = ', id)
I am also getting KeyError's and TypeError: the JSON object must be str, bytes or bytearray, not 'dict'.
Any help is appreciated.
FYI, this is the payload I am wanting to populate with the "name" and "id" values:
data= {
"type":"alert",
"description":"policy",
"enabled":"true",
"filter":{
"type":"match-any-condition",
"conditions":[
{
"field":"extra-properties",
"key":"alertOwner",
"operation":"equals",
"expectedValue":name
}
]
},
"ignoreOriginalResponders": "true",
"ignoreOriginalTags": "true",
"continue": "true",
"name": str(name) + " Policy",
"message":"{{message}}",
"responders":[{"type":"team","id":id}],
"alias":"{{alias}}",
"tags":["{{tags}}"],
"alertDescription":"{{description}}"
}
The JSON response which you have given is already a dictionary so no need to use json.loads for that. The multiple item list is actually nested under the data key. So you could just simply iterate through the array of items like this:
for item in data["data"]:
print("{} : {}".format(item["id"],item["name"]))
This is the output:
02caf2be-3245-4d3d : ORA-FIN-ACTG
03af2f46-fad6-41a1 : NBCMAINFRAME
0649628b-0e3b-48df : CAMS
069d4bcf-3e50-4105 : SHAREPOINTSITE

How to return the last id in JSON using JSON Extractor in JMeter

Here is my response code I want to retrieve the last id always using JSON extractor and further how can I pass this id to another HTTP Request in POST parameter
{
"response": [
{
"dm": "CL 6",
"id": 3,
"yN": "t1-cl -6"
},
{
"dm": "CL 2",
"id": 4,
"yN": "t1- cl -2"
}
],
"timestamp": "2020-04-02T22:40:42.416",
"status": "OK"
}
What I have tried in JSON extractor
but it does not return anything. I even tried $..id[-1]
further, I need to pass this id to another HTTP Request in POST parameter
Use this as JSON Path Expressions: $.response[-1:].id
This will return the last id from the response array objects.
Your configuration should generate the following JMeter Variables:
extract_id_1=3
extract_id_2=4
extract_id_matchNr=2
So the "last" ID can be obtained using __V() function as follows:
${__V(extract_id_${extract_id_matchNr})}
Demo:
More information: Here’s What to Do to Combine Multiple JMeter Variables

How to manipulate json data in Jmeter

In a Jmeter Script, I need to process a http response e manipulate a json for send in next request, because actually this manipulation occurs in a Angular client.
My Http reponse:
[
{
"function":"nameA",
"rast":"F1",
"tag":"EE",
"probs":"0,987"
},
{
"function":"nameB",
"rast":"F2",
"tag":"SE",
"probs":"0,852"
},
{
"function":"nameC",
"rast":"F3",
"tag":"CE",
"probs":"0,754"
}
]
I need convert the result in json bellow to post in next request:
[
{
"function":"nameA",
"rast":"F1",
"type":{
"name":"EE"
},
"id":"alpha"
},
{
"function":"nameB",
"rast":"F2",
"type":{
"name":"SE"
},
"id":"alpha"
},
{
"function":"nameC",
"rast":"F3",
"type":{
"name":"CE"
},
"id":"alpha"
}
]
I filter the response with this JSON Extractor:
[*].["function", "rast", "tag"]
But now I need to solve other problems:
Add an id attribute (same for all functions)
Add an object with the name type.
Move the tag attribute into the object called type.
Rename the tag attribute to the name.
Add JSR223 PostProcessor as a child of the request which returns the original JSON
Put the following code into "Script" area:
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData()).each { entry ->
entry << [type: [name: entry.get('tag')]]
entry.remove('tag')
entry.remove('probs')
entry.put('id', 'alpha')
}
def newJson = new groovy.json.JsonBuilder(json).toPrettyString()
log.info(newJson)
That's it, you should see the generated JSON in jmeter.log file.
If you need to have it in a JMeter Variable add the next line to the end of your script:
vars.put('newJson', newJson)
and you will be able to access generated value as ${newJson} where required
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

extract from a JSON array (JMeter)

what is the best approach to capture from the following array?
i only need to capture the value of ANY 'beginDate', e.g: 2017-05-01T08:30:00 could be a valid one in below example
i need to make sure the 'beschikbaar' = TRUE for the date that i'm capturing
i tried using json path extractor with similar lines: $..[?(#.beschikbaar == 'true')].beginDate but i'm facing syntax errors that i cant fix due to my limited regex/json path knowledge
the example array is;
{
"data":
[
[
{
"beginDate":"2017-05-01T08:00:00",
"eindDate":null,
"beschikbaar":false
},
{
"beginDate":"2017-05-01T08:15:00",
"eindDate":null,
"beschikbaar":false
},
{
"beginDate":"2017-05-01T08:30:00",
"eindDate":"2017-05-01T10:30:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T08:45:00",
"eindDate":"2017-05-01T10:45:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T09:00:00",
"eindDate":"2017-05-01T11:00:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T09:15:00",
"eindDate":"2017-05-01T11:15:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T09:30:00",
"eindDate":"2017-05-01T11:30:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T09:45:00",
"eindDate":"2017-05-01T11:45:00+02:00",
"beschikbaar":true
},
{
"beginDate":"2017-05-01T10:00:00",
"eindDate":"2017-05-01T12:00:00+02:00",
"beschikbaar":true
},
Don't use regular expressions for JSON data, JMeter provides JSON Extractor designed to work with JSON data via JSON Path Language so you should be able to get your "beginDate" with the query like:
$..[?(#.beschikbaar == true)].beginDate
Demo:
Check out JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios article for more detailed explanation and few more examples.
You can try this
(?s)\{.*?\"beginDate\":\"([^{]*?)\"[^{]+\"beschikbaar\":true.*?\}
(?s) is single-line modifier which makes . match the line break
You can test it at http://www.regexplanet.com/advanced/java/index.html
And set Template to $1$ means using the first group

Cloudant Query on dynamic index object

I would like query using the selector for the below JSON object. Based on "Type" my Msgs array displays details.i.e if Type is PAM ,Msgs array will have 'PAMDetails' object. if Type is NAS then NASDetails. Only one type will arrive in the json object. My requirement is to get documents for a given 'LotNumber' and 'messageDate' prior 30 days documents. I tried with default cloudant query but struggling to write the selector for this dynamically creating PAMDetails/NASDetails. tried with Msgs.[].MessageDate but failed to get docs.
{
"_id": "65c5e4c919871f7365f4d814f6e4783g",
"Type": "PAM",
"LotNumber": "11680555",
"Msgs": [
{
"PAMDetails": {
"MessageDate": "2017-01-19"
}
},{
"PAMDetails": {
"MessageDate": "2017-01-21"
}
}
]
}