Search code examples
jmeterbeanshelljsr223

JMeter - JSON response manipulation is not working in JSR223 processor with java


import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;

JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);

String response = prev.getResponseDataAsString();
JSONObject jsonresponse = (JSONObject) p.parse(response);
JSONObject json2 = (JSONObject) jsonresponse.get("Key1");

JSONObject newjson = new JSONObject();
newjson.put("displayValue", json2.get("displayValue"));
newjson.put("value", json2.get("value"));

jsonresponse.put("Key2", newjson);

if(jsonresponse.has("Key3"))
{
    jsonresponse.remove("Key3");
    jsonresponse.put("Key3", jsonresponse.get("Key3").get("value");     
}

log.info(jsonresponse.toString());

I need to enter the if loop to remove the json key value if it exists and replace it with something else.


Solution

    1. I believe you need to change at least if(jsonresponse.has("Key3")) line to if(jsonresponse.containsKey("Key3"))
    2. According to JMeter Best Practices you should not be using Beanshell for scripting so consider switching to Groovy language, Groovy performs much better and moreover it has built-in JSON parsing/generating capabilities. See Apache Groovy - Why and How You Should Use It article for comprehensive explanation, benchmarks, sample code snippets, etc.