Search code examples
groovygroovyshell

Executing variable code in Groovyshell


Consider this piece of code

 def RespJson = RespSlurper.parseText(content)    
 def RespNode= "RespJson"+"."+ assertionKey

where assertionKey will change dynamically on each iteration and will be having values like seatbid[0].bid[0].impid

How can I execute the below code in Groovyshell, I am trying this

def v    
def a = new Binding(RespJson: RespJson)
new GroovyShell(a).evaluate(" v=${RespNode}")
log.info(v)

But I got the value of v as null . Any help is appreciated. Thanks.

EDIT:

def RespSlurper = new JsonSlurper()
def content = step.testRequest.response.responseContent

and the value of content is

{  
   "seatbid":[  
      {  
         "bid":[  
            {  
               "id":"1",
               "impid":"1",
               "price":3.5999999046325684,
               "nurl":"http:...",
               "adomain":[  
                  "zagg.com",
                  "zagg.com"
               ],
               "iurl":"http:...",
               "crid":"30364.s320x50m",
               "h":0,
               "w":0
            }
         ],
         "group":0
      }
   ],
   "cur":"USD",
   "nbr":0
}

Solution

  • I have the code below as what I think is a condensed version of what the question is asking.

    In this case it seems that the v variable can be retrieved off of the binding, which is a. The binding has its variables available on a variables object.

    Also, because the script evaluated by the GroovyShell is the same as what v is set to, printing the output of the GroovyShell object will also print "1".

    import groovy.json.JsonSlurper
    
    def RespSlurper = new JsonSlurper()
    def content = '{"seatbid":[{"bid":[{"id":"1","impid":"1","price":3.5999999046325684,"nurl":"http:...","adomain":["zagg.com","zagg.com"],"iurl":"http:...","crid":"30364.s320x50m","h":0,"w":0}],"group":0}],"cur":"USD","nbr":0}'
    def RespJson = RespSlurper.parseText(content)
    def assertionKey = "seatbid[0].bid[0].impid"
    def RespNode= "RespJson"+"."+ assertionKey
    def v
    def a = new Binding(RespJson: RespJson)
    def result = new GroovyShell(a).evaluate("v=${RespNode}")
    println(v)
    // Important addition!
    println(result)         <=== print the value of the GroovyShell, it will show "1"
    println(a.variables.v)  <=== retrieve the "v" variable off of the binding, it will show "1"