Parse JSON and XML

Applies to ReadyAPI 3.56, last modified on November 21, 2024

You can use Groovy scripts to parse JSON and XML content in your responses and requests.

Where to use

Example

For this example, let's imagine that we have JSON content in the response and XML content in the request, and we want to check that certain values are equal.

{
"info" : {
"buildingStyle" : "MBH.1990",
"owner" : "MBH.1990",
"checkIn" : true,
"checkOut" : true
}
}
<Info>
<BuildingStyle>MBH.1990</BuildingStyle>
<Owner>MBH.1990</Owner>
<CheckIn>true</CheckIn>
<CheckOut>true</CheckOut>
</Info>

Groovy

//Import packages that contain libraries needed to parse JSON and XML
import groovy.json.*
import groovy.util.*

//Parse JSON content in the request
def request = context.expand( '${REST Request#Request}' )
def parsedJson = new JsonSlurper().parseText(request)

//Parse XML content in the response
def response = context.expand( '${REST Request#Response}' )
def parsedXml = new XmlSlurper().parseText(response)

//Assert values in the request against values in the response
assert parsedJson.info.buildingStyle.toString() == parsedXml.BuildingStyle.text()
assert parsedJson.info.owner.toString() == parsedXml.Owner.text()
assert parsedJson.info.checkIn.toString() == parsedXml.CheckIn.text()
assert parsedJson.info.checkOut.toString() == parsedXml.CheckOut.text()

See Also

Groovy Scripting Samples
Scripting

Highlight search results