title: Extract a random value from a JSON response using Groovy in Jmeter
body: <p>I'm trying to set two variables <code>Latitude</code>, <code>Longitude</code> as a random Lat/Long value found in the JSON response. The JSON response contains a <code>Locations</code> 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.</p>
  
  <pre><code>{
    "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
        }
      ]
    }
  }
  </code></pre>
  
  <p>The Groovy Script I'm using is:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>The response I'm getting is long so I will post the important part.</p>
  
  <pre><code>     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:?]
  </code></pre>