Forum Discussion

chir's avatar
chir
Senior Member
6 years ago

json parsing using json slurper

I have done xml parsing using groovy script for reading the response. Can any one tell me how to do the same for JSON Response parsing 

 

Here is the xml parsing script 

 

import com.eviware.soapui.support.XmlHolder
import jxl.*
import java.io.*

def groovyUtils=new com.eviware.soapui.support.GroovyUtils(context)
def holder= groovyUtils.getXmlHolder(messageExchange.responseContent)
//namespaces
def ActualResponse = holder.getNodeValue("//soapenv:Envelope//soapenv:Header//tn:response//hd:field1")
log.info "ActualResponse" + ActualResponse
def myTestCase = context.testCase
Workbook workbook1 = Workbook.getWorkbook(new File("C:\\xyz.xls"))

 

//Need same thing to be handled for JSON ..any one knows this.?

1 Reply

  • Lucian's avatar
    Lucian
    Community Hero

    Hi,

     

    Your question is quite generic. Nevertheless here is a simple Json parsing example.

     

    Let's say we have a request called GetResponse for which the response is as follows:

     

    {
    	"fruits" : 
    		[
    			"bananas",
    			"jabu-ticaba",
    			{
    				"apples" : [ "red", "green" ]
    			},
    			{
    				"oranges" : 
    					[
    						{ "clementines" : "red-clementines" }, 
    						{ "mandarines" : "small-mandarines" }
    					]
    			}
    		]
    }

    In order to parse the json response and select some elements in it the following groovy script can be used:

     

    import groovy.json.JsonSlurper
    
    // Get the response from the GetResponse step
    def response = context.expand('${GetResponse#Response}')
    
    // Parse the response with JsonSlurper
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper.parseText( response )
    
    // Get an element from the json object
    log.info jsonObject.fruits[2].apples

    Here is the full example: https://github.com/lucadln/soapui/tree/master/SoapUIOS/JsonParserExample