How to parse json response using groovy script.
I am using SOAP UI and have json response as below-
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
Can anyone please share sample code to parse json object and post that some basic assertions check.
Thanks
Add a Script Assertion for the rest request test step with below script.
Define your expected data as shown in the snippet below as needed
It compares each key value with expected data.
JsonSlurper can be used to parse the response.
//Check if the response is not empty
assert context.response, 'Response is empty or null'
//Define expected data
def expectedData = [name: 'aaaaaaaaaaa', emailid: 'bbbbbbbbb']
def json = new groovy.json.JsonSlurper().parseText(context.response)
//Checks all elements of resource one by one and compare with expectedData
json.resource.each {k, v -> assert v == expectedData."$k" }
Related
Response from http request:
{"Preferredvalue":{"notations":[]}}
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
I am able to get up to notations and also the size.
If the size is 0, I want to update the notations as below
{"Preferredvalue":{"notations":[{"Name":${firstName},"lName":${lastName}}]}
firstName and lastName are Jmeter variable which are fetched from another calls, and I want to use these values in my another call and send a PUT request.
Searched a lot but couldnt find an answer :(
Best,
Something like:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def notations = response.Preferredvalue.notations
if (notations.size() == 0) {
notations.add([Name: vars.get('firstName'), lName: vars.get('lastName')])
}
def request = new groovy.json.JsonBuilder(response).toPrettyString()
vars.put('request', request)
should do the trick for you. Refer generated value as ${request} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?
POST API is triggering fine and taking only first json object from array and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially using JMeter and Groovy.
json payload : Below is the sample json payload
[
{
"person": "abc",
"Id": "123"},
{
"person": "adfg",
"Id": "12883"},
{
"person": "adf",
"Id": "125"}
]
Groovy code : Reading data from json file which includes multiple json objects and send it to post request in jmeter.
try
{
JsonSlurper jsonSlurper=new JsonSlurper();
def jsonPayload = jsonSlurper.parse(new File('PAYLOAD.json'))
String inputData = new groovy.json.JsonBuilder(jsonPayload)
JsonElement root = new JsonParser().parse(inputData);
JsonArray jsonArray = root.getAsJsonArray();
log.info("jsonArray:"+jsonArray);
if(jsonArray != null && !jsonArray.isEmpty())
{
jsonArray.each{paylodData ->
println paylodData
log.info("post data:"+paylodData);
vars.putObject("payloads", paylodData.toString())
log.info('Generated body: ' + vars.getObject('payloads'))
}
}
}catch (FileNotFoundException fe) {
log.info("Error: Please Check the file path");
}
JMeter Test : Triggering same API with multiple payloads
using below variable in post request body
${payloads}
NOTE : API is triggering fine and taking only first json object and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially.
What are you trying to achieve?
You have a foreach loop which iterates the JSON Array and writes the inner object value into a payloads JMeter Variable
The point is that each iteration of the foreach loop overwrites the previous value in the variable so you will always get the last value.
You either need to replace jsonArray.each with jsonArray.eachWithIndex and store each array member into a separate variable like:
payload_0 = first array member
payload_1 = second array member
etc.
or transform the response into another format, but here I cannot suggest anything because I don't know what is the expected one.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?
I am getting below response from a REST API, but I am finding it difficult to extract label value from the received response and assign it to a variable to use it later in script.
Here is the RESPONSE::
{
"result": "SUCCESS",
"rawAttr": "[{\"attributes\":[{\"name\":\"resourceid\",\"value\":\"7A7Q123456\"},{\"name\":\"physicalid\",\"value\":\"7A7Q123456\"},{\"name\":\"dsw:label\",\"value\":\"MY Product00004285\"},{\"name\":\"dsw:created\",\"value\":\"2019-11-06T08:39:39Z\"}]}]",
"physicalid": "7A7Q123456",
"contextPath": "/path",
"id": "7A7Q123456",
"message": null
}
I am able to get response.id and response.result which is helpful for validation but I am not able to get the dsw:label value which is MY Product00004285
When I do def Arr = response.rawAttr I get the below value whether it is Array or String I am confused. Seems like it is a string.
[{"attributes":[{"name":"resourceid","value":"7A7Q123456"},{"name":"physicalid","value":"7A7Q123456"},{"name":"dsw:label","value":"MY Product00004298"},{"name":"dsw:created","value":"2019-11-06T08:39:39Z"}]}]
It is very easy to extract the label in JMeter JSON Extractor using below JSON Path expression
$.attributes.value[2]
Refer Karate's type conversion capabilities: https://github.com/intuit/karate#type-conversion
So you can do this:
* json attr = response.rawAttr
And then you are all set.
Thanks to an example and documentation on converting string to json.
Got it how to do.
And def strVar = response.rawAttr
And json jsonVar = strVar
And def attrb = karate.jsonPath(jsonVar, '$..attributes.[2].value')[0]
And print '\n\n Attrb\n', attrb
Links I referred:
Json Path evaluator
Karate doc reference for type conversion
Karate example for type-conversion
I need to find json response length. Sample response looks like below:
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
As two parameters are present in resource. So, i should have got response as 2.
Please let me know hoe i can find json length as 2
This is the working solution, try this
import groovy.json.JsonSlurper // import this class
def jsonText = '''{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}'''
def json = new JsonSlurper().parseText(jsonText)
println "Json length---------->"+json.resource.size()
If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following,
println jsonObject.resource.size() // Here resource is the key(sub node) inside your json
If you want to get the length of parent JSON key, just do as follows,
println jsonObject.size()
Based on your question, it appears that you would like to know the count of properties within a JSON object. So we can do that by following these steps:
STEP 1 : Parse the response string into JSON object
STEP 2 : Convert JSON object into groovy Map object
Step 3 : Call size() method on Map object to get the elements count within the map object
So your code would like this :
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')
def object = (Map)response.resource
log.info object.size()
So your output will be 2. You can try adding more elements to JSON object check if it works.
Hope this helps :)
I am trying to learn SoapUI and I have not found any good guides on how to perform a transfer property from a Rest GET request to a Rest POST request.
I have the following payload returned from a REST GET request
{
"a":"a",
"b": { "b1":"b1", "b2":"b2" },
"c":"c"
}
I want to take this JSON and remove c, then submit the rest to a POST request. I wish to post
{
"a":"a",
"b": { "b1":"b1", "b2":"b2" },
}
I am trying to do all this in SoapUI, but have had no success. I am able to get individual values by saying in the source property is RseponseAsXML and the target property is Request. Then I use the command //*:a. But it only returns that value.
I do not want this to be xml though, I am working strictly with JSON.
Thank you.
If you want to manipulate the JSON response to use in other TestStep it's easier to use groovy TestStep instead of Transfer testStep. So create a groovy TestStep and manipulate the response using the following code:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// get the response using the name of your test step
def response = context.expand('${REST Test Request#Response}')
// parse response
def jsonResp = new JsonSlurper().parseText(response)
// remove "c" element
jsonResp.remove("c")
// parse json to string in order to save it as a property
def jsonAsString = JsonOutput.toJson(jsonResp)
log.info jsonAsString // prints --> {"b":{"b1":"b1","b2":"b2"},"a":"a"}
// save the json response without "c" in a testCase property
testRunner.testCase.setPropertyValue('json_post',jsonAsString)
With the code above you parse the response, remove the c element and save as a property in the testCase then in your REST POST you can use the follow code to get your new JSON:
${#TestCase#json_post}
Hope this helps,