How to script on GET Connector's "Edit Expression"?

1
0
-1

First of all, Merry Christmas and Happy New Year 2023!

So I stumbled a roadblock when I use GET Connector to retrieve an API result. Thanks to Mr. Romain, we figure that My API result spits an array of JSON but it appears to be faulty on the structure of the JSON, so I need to use JSONSlurper to change the result into a correct API. I use the "Edit Expression" feature to use JSONSlurper so that the output from the GET Connector can be outputted as a value straight away. But I still can't figure it out how to use this scripting feature cause whenever I test it, it won't work (I figure to use println first as a test and the test return NULL). Here is some snippet of my code :

import groovy.json.JsonSlurper

def bas = bodyAsString
class Example { 
static void main(String[] args, bas) { 
def jsonSlurper = new JsonSlurper() 
def object = jsonSlurper.parseText(bas) 
println(object.name) 
} 
}

I still can't quite figure out how to extract the BodyAsString value to the script, then use the JSONSlurper to parse the text. (If you're wondering what's the output when I test this code, the result is the value of the BodyAsObject itself).

Please help me and love to hear your feedback again. Thanks in advance!

Comments

Submitted by UndergradLads on Mon, 01/09/2023 - 03:15

Hi thanks a lot for your help and it works beautifuly :D

1 answer

1
+1
-1
This one is the BEST answer!

Hi,

You should not redefine a class in a script expression. You can simply write:

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()
println(bodyAsString) // Validate bodyAsString value is the one expected before slurping
def body = jsonSlurper.parseText(bodyAsString)
return body.name

HTH
Romain

Notifications