How do i get JSON values from a response in Groovy

Originally posted by donaldngo on April 25, 2011

Hi I figured out how to grab NodeValue from XML responses in Groovy using:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder (“create a TSA user#Response”)

//Get account ID from the response
context.accountId = holder.getNodeValue (“//accountId”)
log.info (“Storing context.accountId=” + context.accountId );

How would I do the same if the response is in JSON?

Thanks!

Originally posted by thewally on November 02, 2011

I have the same problem. Have somebody a solution for this?

Originally posted by pradeepbishnoi on November 12, 2011

Hi,

Well soapUI handles the JSON response itself and create temporary equivalent XML of the same.
I guess this blog post would be of some help
http://learnsoapui.wordpress.com/2011/0 … ng-soapui/

Best Regards,
~Pradeep Bishnoi~
http://learnsoapui.wordpress.com

Originally posted by sadika on December 22, 2011

you can get Json String from Response using below Groovy Script

import com.eviware.soapui.support.XmlHolder
import net.sf.*;
import net.sf.json.*;
import net.sf.json.groovy.*;

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)

//Getting response from methods
def ResponseMessage = testRunner.testCase.testSteps[“TestStepName”].testRequest.response.contentAsString
def jsonresponse = new XmlHolder(ResponseMessage)
def resonseBody = jsonresponse .prettyXml

now you parse it into Json object and

GJson.enhanceClasses()
def responseAsJsonObject = resonseBody as JSONObject

accountId = responseAsJsonObject[‘responseAsJsonObject’]

Regards,
Sadik Ali

Originally posted by Zakir on December 07, 2012

Guyz,
I guess this is pretty old but I found a easier way using jsonSlurper-

JSON Response-
{
“IDs”: [
1,
27
],
“Items”: {
“1”: {
“ItemName”: “Item1”,
“ItemType”: “Type1”,
“ItemVersion”: 5,
“ItemUrlLocation”: “a/b/c/1.zip”
},
“27”: {
“ItemName”: “Item2”,
“ItemType”: “Type2”,
“ItemVersion”: 5.3,
“ItemUrlLocation”: “a/b/c/d/e/1.zip”
}
},
“status”: {
“responseStatus”: “Success”,
“responseCode”: 200
}
}

Groovy Script

import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*

def ResponseMessage = testRunner.testCase.testSteps[“Req_Name”].testRequest.response.contentAsString
def ItemID, ItemName, ItemType, ItemVersion, i =0
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
log.info “${jsonSlurper.status.responseCode} ${jsonSlurper.status.responseStatus}”
while(jsonSlurper.ItemIDs*!=null){
ItemID = jsonSlurper.ItemIDs ItemName = jsonSlurper.ItemIDs.toString()]ItemName
ItemType = jsonSlurper.ItemIDs*.toString()]ItemType
ItemVersion = jsonSlurper.ItemIDs*.toString()]ItemVersion
log.info “$ItemID::$ItemName::$ItemType::$ItemCriticality::$ItemVersion”
i++
}*****

Originally posted by skolli143 on June 10, 2013

Hi,

I am bit new to Groovy Scripting and handling JSON Resonse .

I have a following JSON Response :
JSON Response :

{
“altmetric_id”: 1492155,
“counts”: {
“readers”: {
“citeulike”: “4”,
“connotea”: “0”
},

“demographics”: {
“poster_types”: {
“member_of_the_public”: 19,
“researcher”: 12,
“practitioner”: 6,
“science_communicator”: 2
},
“geo”: {“twitter”: {
“DK”: 2,
“ES”: 3,
“US”: 17,
“GB”: 1,
“JP”: 3,
“IT”: 1,
“MX”: 2,
“VE”: 2
}}
},

“images”: {
“small”: "https://altmetric-badges.a.ssl.fastly.net/?size=64&score=26&types=fgtttttt",
“medium”: "https://altmetric-badges.a.ssl.fastly.net/?size=100&score=26&types=fgtttttt",
“large”: "https://altmetric-badges.a.ssl.fastly.net/?size=180&score=26&types=fgtttttt"
},
“score”: 25.45,
“last-update-time”: “2013-06-10 14:27:09”,
“created”: “2013-05-30 12:07:39”
}


I need to capture following dates from above response ..
“last-update-time”: “2013-06-10 14:27:09”,
“created”: “2013-05-30 12:07:39”,
Then need to some date related comparisons..

Can anyone let me know how to get “last-update-time” & “created” dates and store in two variables ?

Regards,
Suresh

Originally posted by skolli143 on June 10, 2013

Hi Sadik Ali,

What is “Req_Name” ? , Is it Request name or anything else ?

def ResponseMessage = testRunner.testCase.testSteps[“Req_Name”].testRequest.response.contentAsString

Regards,
Suresh

Originally posted by Holly_Greger on July 08, 2013

This set up worked for me

****json

{
“odata.metadata”: odataCallLocation/@Element",
“EmployeeNumber”: “000000101”,
“nameFirst”: “Soap”,
“nameLast”: “UI”,
}

****groovy script
import com.eviware.soapui.support.XmlHolder
import groovy.json.JsonSlurper

def response = context.expand( ‘${TestStepName#Response}’ ).toString()
log.info(response)

def slurper = new JsonSlurper()
def json = slurper.parseText response

log.info(json.EmployeeNumber)
assert json.nameFirst == “Soap”
assert json.nameLast == “UI”

Originally posted by WillC on June 20, 2016

This thread got me almost there:smileyvery-happy:

I can parse the first level JSON correctly (thank you). The second level JSON, however, I am not getting counted as I had hoped I would. Any ideas on how to get the selected count to work?

I) JSON File

{
“totalResults”: 7,
“limit”: 100,
“offset”: 0,
“items”: [
{
“resourceId”: “33100000”,
“status”: “active”,
“parentResourceId”: “33000001”,
“resourceType”: “BK”,
“name”: “North”,
“language”: “en”,
“timeZoneDiff”: -102,
“timeZone”: “Eastern”,
“dateFormat”: “mm/dd/yy”,
“timeFormat”: “24-hour”,
“inventories”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33100000/inventories”
}]},
“users”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33100000/users”
}]},
“workZones”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33100000/workZones”
}]},
“workSkills”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33100000/workSkills”
}]},
“links”: [
{
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33100000”
},
{
“rel”: “describedby”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/metadata-catalog/resources”
}
]
},
{
“resourceId”: “33200000”,
“status”: “active”,
“parentResourceId”: “33100000”,
“resourceType”: “PR”,
“name”: “BERTUZZI, Todd \t”,
“email”: “[email protected]”,
“phone”: “555003310300”,
“language”: “en”,
“timeZoneDiff”: -102,
“timeZone”: “Eastern”,
“dateFormat”: “mm/dd/yy”,
“timeFormat”: “24-hour”,
“inventories”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33200000/inventories”
}]},
“users”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33200000/users”
}]},
“workZones”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33200000/workZones”
}]},
“workSkills”: {“links”: [ {
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33200000/workSkills”
}]},
“links”: [
{
“rel”: “canonical”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/resources/33200000”
},
{
“rel”: “describedby”,
“href”: “http://demo-ofsc.etadirect.com/rest/ofscCore/v1/metadata-catalog/resources”
}
]
},
{
“resourceId”: “33400000”,
“status”: “active”,
“parentResourceId”: “33100000”,
“resourceType”: “PR”,
“name”: “FIDDLER, Vernon”,
“email”: “[email protected]”,
“phone”: “5555771002”,
“language”: “en”,
“timeZoneDiff”: -102,
“timeZone”: "Easte

II) Working Groovy Script to “get” totalResults

import com.eviware.soapui.support.XmlHolder
import groovy.json.*

//define the location of the JSON file
def response = context.expand( ‘${get_descendants#Response}’ ).toString()

//define “json” which will be the name of my variable
def json = new JsonSlurper().parseText (response)

//grab that json file result I want
log.info json.totalResults

III) Non-Working Groovy Script to “get” resourceId

package json

import com.eviware.soapui.support.XmlHolder
import groovy.json.*

//define the location of the JSON file
def response = context.expand( ‘${get_descendants#Response}’ ).toString()
//log.info(response)

//define “json” which will be the name of my variable
def json = new JsonSlurper().parseText (response)

//grab that json file result I want
log.info json[1].items.resourceId
log.info json[1].items.name
log.info json[1].items.resourceType
log.info json[1].items.status

Anyone see what is wrong here with the count?

Originally posted by nmrao on June 20, 2016

Here is the later part of the script:

It was not working because, items is a Json Array.

json.items.eachWithIndex{ item, index ->
  log.info "Item #: ${index}"
  log.info "Item resource Id: ${tem.resourceId}"
  log.info "Item name : ${item.name}"
  log.info "Item resource type : ${item.resourceType}"
  log.info "Item status : ${item.status}"}

Originally posted by WillC on June 20, 2016

Thank you Rao. That makes perfect sense. This withEachIndex is exactly what I was looking for. I suspect this will help others as well. I am still throwing an error after many editing attempts. I’ve done some searching…not sure what is missing with a find or subsequent step. Thank you, again.

I) Current JSON Parser

package json

import com.eviware.soapui.support.XmlHolder
import groovy.json.*

//define the location of the JSON file
def response = context.expand( ‘${get_descendants#Response}’ ).toString()
//log.info(response)

//define “json” which will be the name of my variable
def json = new JsonSlurper().parseText (response)

json.items.eachWithIndex
{
item, index →
log.inf “totalResults: ${index}”
log.inf “Item resourceId: ${item.resourceId}”
log.info “Item name: ${item.name}”
log.info “Item resource type: ${item.resourceType}”
log.info “Item status: ${item.status}”
}

II) Error Message thrown (if I comment out totalResults line same error occurs for subsequent lines):

groovy.lang.MissingMethodException:

No signature of method: org.apache.log4j.Logger.inf() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [totalResults: 0]

Possible solutions: info(java.lang.Object), find(), any(), info(java.lang.Object, java.lang.Throwable), is(java.lang.Object), find(groovy.lang.Closure)

Originally posted by WillC on June 20, 2016

Problem resolved. Typo only. Below is the working indexed code for future reference:

package json

import com.eviware.soapui.support.XmlHolder
import groovy.json.*

//define the location of the JSON file
def response = context.expand( ‘${get_descendants#Response}’ ).toString()

//log.info(response)

//define “json” which will be the name of my variable
def json = new JsonSlurper().parseText (response)

json.items.eachWithIndex
{
item, index →
log.info “totalResults: ${index}”
log.info “Item resourceId: ${item.resourceId}”
log.info “Item name: ${item.name}”
log.info “Item resource type: ${item.resourceType}”
log.info “Item status: ${item.status}”
}

Originally posted by nmrao on June 20, 2016

Good catch. Thank you for fixing typo for your self. By the fixed typo.