JMeter - How to read JSON file?

17k Views Asked by At

I used the CSV format for the data files in JMeter. Our VP wants to change the format to JSON. How can I read a JSON file from the disk?

2

There are 2 best solutions below

2
On BEST ANSWER

You have at least 2 options:

  1. Use HTTP Request sampler and file protocol like:

    HTTP Request File Protocol

    JSON files are basically plain-text files so you will be able to use JSON Extractor or JSON Path Extractor to parse JSON data and store the result into JMeter Variables for later reuse

    References:

  2. Use JSR223 Test Elements and Groovy language. Groovy has built-in JSON support via JsonSlurper so you will be able to parse the JSON file programmatically.

    References:

0
On

The best solution for this problem is to use JSR223 Sampler to read JSON file and load into the vars or props and use it wherever it is required.

For this,

  1. Add a JSR223 Sampler in JMeter
  2. Add the below code
import java.io.File
import java.util.Base64


def propertiesFromMap(map, prefix) {
    for (item in map) {
        id = prefix+item.key;
        if (item.value instanceof Map) {
            propertiesFromMap(item.value, id+".");
        } else {
            value = item.value.toString();
            log.info("Loading property " + id + ": " + value);
            if(value.startsWith("ENC:")) {
                props.put(id, new String(Base64.getDecoder().decode(value.substring(4, value.length()))));
            } else {
                props.put(id, value);
            }
        }
    }
}

def baseDir = org.apache.jmeter.services.FileServer.getFileServer().getBaseDir();
def jsonFilePath= baseDir + "/configs/" + "configuration-dev" + ".json";
log.info("Loading properties from " + jsonFilePath);
def jsonMap = new groovy.json.JsonSlurper().parse(new java.io.File(jsonFilePath));
propertiesFromMap(jsonMap, '');
  1. Create a directory named configs where you placed the .jmx file
  2. Create a file named configuration-dev.json in configs directory
  3. Add JSON content e.g. in the file:
{
   "key1": "value1",
   "key2": "value2",
   "key3": "ENC:base64_encoded_value"
   "group1": {
      "grp1_key": "value"
   }
  1. Access values in Samplers e.g. ${__P(key1)}, it will return value of key1. For group1 variables access e.g. ${__P(group1.grp1_key)}
  2. For accessing the values into JSR223 use props e.g. props.get("key1")
  3. You can pass base64 encoded values into JSON by adding ENC: as value prefix which will be resolved automatically when accessing values from props or __P()