Search code examples
jmeterjmeter-5.0jsr223

JSR223 Assertion : Passing a custom key to JsonOutput.toJson()


I am doing a validation using the following code:

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

String sourceTargetPassJson = "{\"Apple\":[\"Apple\",\"Orange\",\"Kiwi\",\"Avocado\"],\"Orange\":[\"Orange\",\"Kiwi\",\"Avocado\"]}";

def sourceVar = vars.get("source_type");
def targetVar = vars.get("target_type");

log.info("Source :" + sourceVar + ", Target :" + targetVar + ".");

def jsonSlurper = new JsonSlurper();
def response = jsonSlurper.parseText(sourceTargetPassJson);

def json = JsonOutput.toJson(response.sourceVar);

log.info("Response: " + json);

vars.put("json", json);

Here, the def json = JsonOutput.toJson(response.sourceVar); is failing because there is no key called sourceVar, which is obtained based on the Jmeter variable source_type. Given that the above assertion is in a loop controller, I want to validate based on the source_type obtained on each iteration.

Example :

Iteration 1, sourceVar = "Apple", json should have ["Apple","Orange","Kiwi","Avocado"]. Iteration 2, sourceVar = "Orange", json should have ["Orange","Kiwi","Avocado"].

How do I obtain the value for the variable json here based on the custom value of sourceVar?


Solution

  • The issue was simply resolved by the following change :

    String json = response[sourceVar];
    

    So, if the sourceVar is "Apple", the value of json obtained is [Apple,Orange,Kiwi,Avocado]