0
votes
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.

1
Getting the below error: - Om Prakash Yadav
JSR223PostProcessor: Problem in JSR223 script, JSR223 PostProcessor javax.script.ScriptException: Sourced file: inline evaluation of: import net.minidev.json.parser.JSONParser; import net.minidev.json.JSONObject; i . . . '' : Typed variable declaration : Undefined argument: Key3 : at Line: 17 : in file: inline evaluation of: import net.minidev.json.parser.JSONParser; import net.minidev.json.JSONObject; i . . . '' : ( Key3 ) in inline evaluation of: ``import net.minidev.json.parser.JSONParser; import net.minidev.json.JSONObject; i . . . '' at line number 17 - Om Prakash Yadav
Key1 & Key3 are part of the json response - Om Prakash Yadav
Please edit your question and add all of the relevant information in the body of the question, not as comments. - David Buck

1 Answers

1
votes
  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.