Groovy - JSONSlurper parsing json - json

I have problem with my SoapUI Groovy script. I have following json (simplified):
{
"data":{
"XXX":[...]
"YYY":[...]
},
"next":"ffawef234fava23r"
}
I have values of XXX and YYY in my previously TestStep as request parameters and I extract it properly as list of string, but my problem is that I need to extract content of data.XXX and data.YYY, but when I want to do this in loop I always get null. My code:
def content = new JsonSlurper().parseText(response)
def ids = extracted_ids.split(';') //List of IDs in response above {XXX,YYY}
for (id in ids){
log.info id // XXX
log.info content.data.'XXX' //this works
log.info content.data.id //this not
}
Is there any option to pass this "id" in loop to content.data.{id} to get any content instead of null
Kind Regards

You just need to do
log.info content.data."$id"

Related

Groovy script json response length

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 :)

groovy script SOAP UI json response parse

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" }

Getting the only key of a Map from JsonSlurper

I have JSON that needs to be processed using Groovy. I am pretty sure that the JSON has only one key, with this format:
{ rootKey: [...] }
Where rootKey stands for different values (e.g. "customers", "stores", etc.).
Let's say I used JsonSlurper:
def map = jsonSlurper.parseText(myjson)
How do I obtain that rootKey string?
You should be able to use keySet method to get the keys which is a list. Since, you mentioned only key, you can use the first element as shown below:
def jsonString = """{
"rootKey": []
}"""
def json = new groovy.json.JsonSlurper().parseText(jsonString)
println json.keySet()[0]

Get a parent value based on child value in SoapUI

In the response Json, getting an array list of items as shown.
What you see in the question is not xml, it is a json string. So, xpath does not work.
For your request test step, you can add the Script Assertion as shown below:
//Check the response
assert context.response, 'Response is empty or null'
//Expected subscription id, change it if needed
def expectedSubscriptionId = '2c92c0f95ae1445b015af2320235689f'
def parsedJson = new groovy.json.JsonSlurper().parseText(json)
def ids = [] as Set
parsedJson.each { item ->
item.amendments.each { amendment ->
if (amendment.subscriptionId == expectedSubscriptionId ) {
ids << item.id
}
}
}
assert ids.size(), "id's are not found in the response for matching subscription"
log.info "Matching id's are : ${ids}"
You may quickly try online Demo

Grails: Easy and efficient way to parse JSON from a Request

Please pardon me if this is a repeat question. I have been through some of the questions/answers with a similar requirement but somehow got a bit overwhelmed and confused at the same time. My requirement is:
I get a JSON string/object as a request parameter. ( eg: params.timesheetJSON )
I then have to parse/iterate through it.
Here is the JSON that my grails controller will be receiving:
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
Questions:
How can I retrieve the whole JSON string from the request? Does request.JSON be fine here? If so, will request.JSON.timesheetJSON yield me the actual JSON that I want as a JSONObject?
What is the best way to parse through the JSON object that I got from the request? Is it grails.converters.JSON? Or is there any other easy way of parsing through? Like some API which will return the JSON as a collection of objects by automatically taking care of parsing. Or is programatically parsing through the JSON object the only way?
Like I said, please pardon me if the question is sounding vague. Any good references JSON parsing with grails might also be helpful here.
Edit: There's a change in the way I get the JSON string now. I get the JSON string as a request paramter.
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def object1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now.
I have wrote some code that explains how this can be done, that you can see below, but to be clear, first the answers to your questions:
Your JSON String as you wrote above will be the contents of your POST payload to the rest controller. Grails will use its data binding mechanism to bind the incomming data to a Command object that your should prepare. It has to have fields corresponding to the parameters in your JSON String (see below). After you bind your command object to your actual domain object, you can get all the data you want, by simply operating on fields and lists
The way to parse thru the JSON object is shown in my example below. The incomming request is esentially a nested map, with can be simply accessed with a dot
Now some code that illustrates how to do it.
In your controller create a method that accepts "YourCommand" object as input parameter:
def yourRestServiceMethod (YourCommand comm){
YourClass yourClass = new YourClass()
comm.bindTo(yourClass)
// do something with yourClass
// println yourClass.timeSheetList
}
The command looks like this:
class YourCommand {
String loginName
List<Map> timesheetList = []
String overallStatus
void bindTo(YourClass yourClass){
yourClass.loginName=loginName
yourClass.overallStatus=overallStatus
timesheetList.each { sheet ->
TimeSheet timeSheet = new TimeSheet()
timeSheet.periodBegin = sheet.periodBegin
timeSheet.periodEnd = sheet.periodEnd
sheet.timesheetRows.each { row ->
TimeSheetRow timeSheetRow = new TimeSheetRow()
timeSheetRow.task = row.task
timeSheetRow.description = row.description
timeSheetRow.paycode = row.paycode
timeSheet.timesheetRows.add(timeSheetRow)
}
yourClass.timeSheetList.add(timeSheet)
}
}
}
Its "bindTo" method is the key piece of logic that understands how to get parameters from the incomming request and map it to a regular object. That object is of type "YourClass" and it looks like this:
class YourClass {
String loginName
Collection<TimeSheet> timeSheetList = []
String overallStatus
}
all other classes that are part of that class:
class TimeSheet {
String periodBegin
String periodEnd
Collection<TimeSheetRow> timesheetRows = []
}
and the last one:
class TimeSheetRow {
String task
String description
String paycode
}
Hope this example is clear enough for you and answers your question
Edit: Extending the answer according to the new requirements
Looking at your new code, I see that you probably did some typos when writting that post
def jsonArray = jsonArray.timesheetList
should be:
def jsonArray = jsonObject.timesheetList
but you obviously have it properly in your code since otherwise it would not work, then the same with that line with "println":
jsonArray1.size()
shuold be:
jsonArray.size()
and the essential fix:
def object1 = jsonArray[1]
shuold be
def object1 = jsonArray[0]
your array is of size==1, the indexing starts with 0. // Can it be that easy? ;)
Then "object1" is again a JSONObject, so you can access the fields with a "." or as a map, for example like this:
object1.get('periodEnd')
I see your example contains errors, which lead you to implement more complex JSON parsing solutions.
I rewrite your sample to the working version. (At least now for Grails 3.x)
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON)
println jsonObject.timesheetList // output timesheetList structure
println jsonObject.timesheetList[0].timesheetRows[1] // output second element of timesheetRows array: [paycode:payCode2, task:painting, activityDescription:painting description]