JSR223 Tips and Tricks Part 4

In this post we are going to continue using the same script from Part 3.  This is a simple example which demonstrates how to update a single field value in the JSON body data.

First right-click to add a JSR223 Post Processor to the test script:

01_postproc

Next select groovy as the programming language and paste the following code.  Note that we are using two groovy jars (1) JsonSlurper (2) JsonBuilder

import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

//parse json using JsonSlurper
def slurpy = new JsonSlurper().parseText(vars.get("jsonBodyData"))

//update field value "custname" and rebuild json using JsonBuilder
def builder = new JsonBuilder(slurpy)

//update value of custname field
builder.content.custname = 'NewName'
vars.put("jsonBodyData", builder.toPrettyString()) 
log.info("builder = " + "\n" + builder.toPrettyString())

Now open the log viewer and run the script, the output should look like this:

02_viewer