I'm trying to set two variables Latitude
, Longitude
as a random Lat/Long value found in the JSON response. The JSON response contains a Locations
array containing a list of Lat/Long values. Every time this script is ran, I want my variable to be set to random lat/long values from the Locations array. The Groovy script is a JSR223 PostProcessor with the nested within the POST HTTP request. Below I will post an example response and the Groovy code to achieve this.
{
"Result": {
"Locations": [
{
"Latitude": 38.657,
"Longitude": -120.377997
},
{
"Latitude": 38.6566,
"Longitude": -120.3791
},
{
"Latitude": 38.658399,
"Longitude": -120.3804
},
{
"Latitude": 38.655499,
"Longitude": -120.38496
},
{
"Latitude": 38.654,
"Longitude": -120.3819
},
{
"Latitude": 38.6537,
"Longitude": -120.3897
},
{
"Latitude": 38.6544,
"Longitude": -120.382604
},
{
"Latitude": 38.655602,
"Longitude": -122.386402
}
]
}
}
The Groovy Script I'm using is:
import groovy.json.*
//Parse JSON
def jsonSlurper = new JsonSlurper();
def response = jsonSlurper.parseText(prev.getResponseDataAsString())
def LocationsList = JsonOutput.toJson(response.Result.Locations)
//Get the size of Locations Array and Generate Random Number based on array size
Random random = new Random()
int max = LocationsList.size()
int randomNumber = random.nextInt(max)
//Get Latitude
def GetLatitude (number) {
return LocationsList[number].Latitude
}
def Latitude = GetLatitude(randomNumber)
//Get Longitude
def GetLongitude (number) {
return LocationsList[number].Longitude
}
def Longitude = GetLongitude(randomNumber)
//Set the env vars
vars.put("Latitude", Latitude)
vars.put("Longitude", Longitude)
The response I'm getting is long so I will post the important part.
Problem in JSR223 script, CurrentGPS
javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: LocationsList for class: Script18
at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:320) ~[groovy-all-2.4.13.jar:2.4.13]
at org.codehaus.groovy.jsr223.GroovyCompiledScript.eval(GroovyCompiledScript.java:72) ~[groovy-all-2.4.13.jar:2.4.13]
at javax.script.CompiledScript.eval(CompiledScript.java:92) ~[java.scripting:?]
There are couple of issue in your script:
LocationsList
is incorrectly getting value.LocationsList
is being accessed in both the methods which is not scope. You could have used Closure
instead.Here is the fixed script:
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
def locations = json.Result.Locations
def randomNumber = new Random().nextInt(locations.size())
def latitude = locations[randomNumber].Latitude
def longitude = locations[randomNumber].Longitude
You can quickly try the online demo