简体   繁体   中英

Extract a random value from a JSON response using Groovy in Jmeter

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

In case when JSON Path expression returns multiple matches you can get a random one without any scripting using JSON Extractor . The component is available since JMeter 3.0 and given you provide 0 as "Match No" it will return random value from whatever your JSON Path Expression matches. The configuration would be something like:

JMeter JSON提取器配置

Text representation:

  • Names of created variables: Latitude;Longitude
  • JSON Path Expressions: $..Latitude;$..Longitude
  • Match No: 0
  • Default Values: NA;NA

Thanks guys this is very helpful, I need help how to use condition statement in this code, below is the sample JSON:

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sword of Honour",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "test_title",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Sword of Honour",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "India",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
} 

In this if my title is " Sword of Honour " than pull price and author and each iteration different which I think Random can do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM