Is it possible to trim JSON object in response using Jmeter? - json

JSON response returns an object with the following value.
2019-03-20T14:51:30.579+0000
I want to ignore the .579+0000 part for my validation. How can I trim it from the actual value so that I get:
2019-03-20T14:51:30

I would recommend parsing the object value as a Date, this way you will have possibility to convert it to whatever format you like.
Given you have the following JSON response:
{
"someObject": "2019-03-20T14:51:30.579+0000"
}
You can do the transformation as follows:
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
def originalDate = new groovy.json.JsonSlurper().parse(prev.getResponseData()).someObject
log.info("Original date: " + originalDate)
vars.put("myDate", Date.parse("yyyy-MM-dd'T'HH:mm:ss.SSSX", originalDate).format("yyyy-MM-dd'T'HH:mm:ss"))
log.info("Converted date: " + vars.get("myDate"))
you will need to amend this someObject bit with the path to the JSON attribute holding this date. Once done you should be able to access the "trimmed" data as ${myDate} where required.
References:
SimpleDateFormat
Groovy: Parsing and producing JSON
Groovy Goodness: Working with Dates
The Groovy Templates Cheat Sheet for JMeter

Related

How to validate JSON's specific element against DB data in JMeter

I want to perform validation of JSON response against DB data.
For example I have a student table with column as "StudentID" , "StudentName" and "StudentAddress"
and In JSON response we have element as "StudentNumber", "StuName" and "StuAddress" (Name is different in both JSON and DB)
Question 1: How can I compare entire JSON against the DB data to match it in JMeter.
Question 2: If I want to perform validation like if in Database "StudentID"=1 then in JSON response "StudentNumber" should be equal to "A". How can I validate it in JMeter in a single script
If you want to compare entire JSON to the result of the database query which returns more than 1 row - the only option is going for JSON Assertion and implementing your pass/fail criteria in Groovy.
Groovy has built-in JSON support so it can parse the response as JSON and convert it to maps/lists/values
Groovy can iterate the ResultSet object containing the query results, see Debugging JDBC Sampler Results in JMeter for more details
If you want to compare individual entries:
In the JDBC Test Element specify variable name to store the value from the database
Use JSON Extractor or JSON JMESPath Extractor to store the value from JSON
Compare 2 variables using Response Assertion
Following is a sample code used within a JSR223 element to process JSON response
import groovy.json.JsonSlurper
try{
def responseJSON = prev.getResponseDataAsString()
if(responseJSON) {
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(responseJSON)
def itemCount = object['items']['id'].size()
log.info("Items $itemCount")
for (i in 0..<itemCount){
log.info("Student Number ${object['items']['id'][i]}")
log.info("Student Name ${object['items']['studentName'][i]}")
log.info("Address ${object['items']['address'][i]}")
}
}catch (anything){
log.info("Error ")
}
Groovy has support for working with JSON. Documentation.

Obtain value in json response

How do i write an expression to obtain the value "lastUpdated" in the below json response data
{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00",
I have tried this but it does not work:
regex("\"lastUpdated\": \"(.*?)\"").saveAs("lastUpdated")
this also does not work:
jsonPath("$..[?(#.use==\"lastUpdated\")].value").saveAs("lastUpdated"))
Your input is a little cut off but here is what I've got:
myJSONString = '{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00"}}}]}'
myJSONObject = JSON.parse(myJSONString)
myLastUpdated = myJSONObject.parameter[0].resource.meta.lastUpdated
console.log(myLastUpdated)
Basically you convert it from a json object into a javascript object. Then you can just traverse down the tree to your intended target.

How to extract the Substring from URL present in JSON response using JMeter

I've the below JSON response received from the HTTP request. I want to extract the parameters from the node "url" present in the JSON response.
{"Id":"7S9LyBqyv1e0trKrVuP1OOZGHeg","Url":"https://abcd.com:443/u/custom-response?prov=34545sdf-9013e2e61e66&realmeId=%2Fxxxx","realmeId":"/abcd"}
In the above JSON response, i want to retrieve the value of "prov" which is 34545sdf-9013e2e61e66 using JMeter.
Solution Tried: Used Beanshell to read the response.
String url = vars.get("successURL");
vars.put("responseURL",url.toString());
responseURL = responseURL.replaceAll(":"," ");
log.info("String URL "+responseURL.toString());
Error Message:
attempt to resolve method: toString() on undefined variable or class name: responseURL
I think you need to update this line:
responseURL = responseURL.replaceAll(":"," ");
to something like:
responseURL = vars.get("responseURL").replaceAll(":"," ");
However I don't guarantee that it will work because I don't know how do you get this successURL variable.
What will work is doing everything in one shot using JSR223 PostProcessor and Groovy language which has built-in JSON support, suggested code:
def url = new groovy.json.JsonSlurper().parse(prev.getResponseData()).Url
def params = org.apache.http.client.utils.URLEncodedUtils.parse(new URI(url), 'UTF-8')
params.each { param ->
log.info(param.getName() + '=' + param.getValue())
}
Demo:
More information: Apache Groovy - Why and How You Should Use It
You don't need to use complex Beanshell coding, You can do this easily using - Regular Expression Extractor.
Here the example:-
You can see required value extracted and stored in variable name give in Regular expression extractor:
To understand try out reg-ex, you can use https://regex101.com/

extract a concrete part of a value from a Response to a new string Groovy script

I'm kinda new in groovy and I need help
I need to write a groovy script to transform or else extract a concrete value from a Json Response to a new string Groovy script.
and the groovy script I used is this one :
responseJson = testRunner.testCase.getTestStepByName("Test Scenario").getPropertyValue("response")
parsedResponse = slurper.parseText(responseJson)
log.info(parsedResponse["items"]["/ticket_id"])
My generated string response from the groovy script I use looks like this:
/ticket_id":"{\"isTodo\":false,\"items\":[[\"WhatIwantToExtract\",\"\",\"url.com:blablabla_qc_vpc-11:Machine:data-da-data\",timestamp]]}
The response is correct in fact but I just want to extract a piece of this
The data I wanted to extract is labeled above as " WhatIwantToExtract " without the commas.
I solved it
def regexResult = (parsedResponse["items"][0][0])

How to make sure that JSON extractor always gets the proper value from response?

I am using JSON extractor to parse the response but sometimes the response return a blank value in the given index and that time I want to make sure that we move to another index to get the proper value.
For e.g. my JSON path expression is
$.CM[0].id
When application returns a blank value in the 0 index, that time I get the default value which is mentioned in the JSON extractor, instead what I want is whenever my script returns a blank value for 0 index, script should search for the value in next index i.e. 1. So when $.CM[0].id fails to get the value, application should search for $.CM[1].id and get the response.
What should be my approach? Should I use some sort of bean shell scripting or should try to use if controller?
I would recommend switching to JSR223 PostProcessor and Groovy language.
Add JSR223 PostProcessor as a child of the request which returns JSON response
Put the following code into "Script" area:
def ids = new groovy.json.JsonSlurper().parse(prev.getResponseData()).CM.ID
ids.eachWithIndex { id, i ->
log.info('Trying id: ' + i)
if (id.size() > 0) {
log.info('Found non-empty ID: ' + id)
vars.put('ID', id)
return true
}
}
The above code will put a non-empty ID value (if any) into ID JMeter Variable, you will be able to refer extracted value as ${ID} or ${__V(ID)} where required.
References:
Groovy Parsing and producing JSON
Groovy Each Loop Examples
Groovy is the New Black