0

Below is Groovy code that is part of ReadyAPI test. A key, value pair is read from an excel sheet and replaced in the Json string. Issue is not sure how to execute the command stored in the variable "var". This is supposed to dynamically replace the value in the Json string. I tried to use Eval.me and some other, but non worked. Thanks for everyone's input/suggestions in advance.

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def req = context.expand( '${Update Bet#RawRequest}' )
def slurperReq = new JsonSlurper().parseText(req)
def excelKey = context.expand( '${DataSource#Key}' )     // Key read from Excel sheet
def excelValue = context.expand( '${DataSource#Value}' ) // Value read from Excel sheet
def actualValue = slurperReq."$excelKey"         // Gets the sctual value for Key "modifiedAt"

//slurperReq.modifiedAt="@@@@@@@@@@@" // This will correctly replace the value for the given key "modifiedAt"

String  var="slurperReq."+excelKey+"=\"@@@@@@@@@@@\"" 
log.info var // Correctly prints >>   slurperReq.modifiedAt="@@@@@@@@@@@"
//*** What should go here to execute the string stored in var, which replace
// the value for key "modifiedAt" ***
def jsonReq = JsonOutput.toJson(slurperReq)
log.info jsonReq
user10829672
  • 35
  • 2
  • 10

1 Answers1

0

you don't need any dynamic execution if you want to set new value into a map (json object)

there are different ways to do that:

def slurperReq = [a:"hello",b: "world"]
def excelKey = "modifiedAt"
// here are three different ways to set new value 
// into a map for the key stored  in a string varable
slurperReq[excelKey] = "@@@@@@@@@@@"
slurperReq."$excelKey" = "@@@@@@@@@@@"
slurperReq.put(excelKey, "@@@@@@@@@@@")

println groovy.json.JsonOutput.toJson(slurperReq)

the code above prints json with a new value

{"a":"hello","b":"world","modifiedAt":"@@@@@@@@@@@"}
daggett
  • 26,404
  • 3
  • 40
  • 56