In ReadyAPI I have a JSON response like:
{
"Example" : [
{
"Name" : "Name_1",
"Id" : 20100202141652076488478
}]
}
Now, I want to get this Id using Groovy and save it to a property in ReadyAPI. The problem is that this number is too large and is changed to -6748898691334772962
Before using JsonSlurper I see that the value is correct. After JsonSlurper it changes to -6748898691334772962
What are my options to retain 20100202141652076488478?
You can use
import grails.converters.JSON
def json = JSON.parse(yourJson)
20100202141652076488478 comes out correctly as java.math.BigInteger
Related
I have a JSR223 Assertion in JMeter that validates entire JSON response and its working.
The problem is that each time I insert data in DB one of JSON fields changes and validation fails.
How could I skip that dynamic field from response validation?
Response JSON example:
[
{
"id": "273444",
"trxDateTime": "2019-03-25T22:38:16Z",
"merchantName": "MerchECOM1",
"merchantTransId": "1r1vXue4qn",
"trxType": "Payment",
"paymentBrand": "MasterCard",
"amount": 20.00,
"currencyCode": "AUD",
"status": "Declined",
"statusResponseMessage": null,
"customerAccount": "123456"
}
]
JSR223 Assertion:
def expected = new groovy.json.JsonSlurper().parseText(vars.get('expected1'))
def actual = new groovy.json.JsonSlurper().parse(prev.getResponseData())
if (expected != actual) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Mismatch between expected and actual JSON')
}
just with this I'm not able to validate the dynamic "id" field
any idea?
Thanks in advance
If you're not interested in this id field - just remove it from the expected variable and the actual response, to wit amend first 2 lines of your assertion to look like:
def expected = new groovy.json.JsonSlurper().parseText(vars.get('expected1')).each {entry -> entry.remove('id')}
def actual = new groovy.json.JsonSlurper().parse(prev.getResponseData()).each {entry -> entry.remove('id')}
More information:
Groovy: Parsing and Producing JSON
Apache Groovy - Why and How You Should Use It
Demo:
If value is not your concern for id field you can directly use regex matcher to check the field using Jsonassertion by specifying jsonpath and check match as regex use regex
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'm using JSON Path PostProcessor with path expressions to store a JSON object from a JSON response, but when I later retrieve the variable, it has been reduced to string with key - pair values. So I don't know that was a string or number.
Example:
Response looks like this
{
.
.
"currency" : {
"code" : "AUD",
"name" : "Australian Dollars",
"symbol" : "$"
},
.
}
Using the path expression, I find currency and save it.
However, when I use it in a HTTP Request body data ("currency" : ${currency},),
it comes like this:
"currency" : {code=AUD, name=Australian Dollars, symbol=$},
How do I get the JSON Path PostProcessor to save the JSON object 'as is" without losing the data type details? Should I be using a different approach instead of JSON Path?
I would recommend switching to JSR223 PostProcessor and Groovy language, this way you will have full control of what is going on and be able to do what you want.
Assuming you have the following JSON response:
{
"currency": {
"code": "AUD",
"name": "Australian Dollars",
"symbol": "$"
}
}
the relevant Groovy coode will be something like:
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def currency = json.currency
def currencyString = new groovy.json.JsonBuilder(currency).toPrettyString()
vars.put('currency', currencyString)
log.info(currencyString)
Demo:
References:
Groovy - Learn
Groovy - Parsing and producing JSON
Groovy is the New Black
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,
I use JsonBuilder to build a JSONObject/String.
But, how can I update/change value of one field in this JSONObject/String?
I am not seeing the possibility of doing this using JsonBuilder. What show I use then?
If you have to change the content you already put into the JsonBuilder, then you could do:
import groovy.json.*
def map = [ users:[ [ name:'tim', posts:43 ], [ name:'alice', posts:72 ] ] ]
JsonBuilder builder = new JsonBuilder( map )
builder.content.users[ 0 ].name = 'dave'
assert builder.toString() == '{"users":[{"name":"dave","posts":43},{"name":"alice","posts":72}]}'
But as content is not explicitly exported from the Object, I'd call this a side-effect and would not rely on it working in future versions of Groovy.
Better to get your map right before you pass it to JsonBuilder, or if that isn't possible I guess you'll need to parse the Json string with JsonSlurper modify the resulting Map and then rebuild the Json with JsonBuilder again.