简体   繁体   中英

Jmeter Groovy replacing JSON file

In Jmeter JSR223Preprocessor with Groovy I load a generic JSON file xyz looking like this:

    {
  "name": "dummy",
  "block1": {
    "var1": 1,
    "var2": {
"value": 1,
  "unit": "Miles",
 },  
    "var3": {
"value": 3,
  "unit": "Seconds",
 },  
  "myList": [{"Id": 0}]
}

I like to come up with an elegant way to replace the var2 "Value" with a configurable value sayconfVal. This works:

String path = vars.get("basePath")+"xyz.json" ;
xyz = new File(path).getText("UTF-8");
xyz = xyz.replaceAll ('"value": 1', '"value": ${confVal}');

However I am not comfortable with this because it is vulnerable with spaces, and moreover I have another Value on var3 and someone could accidentally change 1 to 3. So I like to index to that child var2.Value then get Value. Thank you

  1. Add JSR223 PreProcessor as a child of the HTTP Request which body you need to amend
  2. Put the following code into "Script" area:

     def xyz = new File(vars.get("basePath")+"xyz.json") def request = new groovy.json.JsonSlurper().parse(xyz) request.block1.var2.value=vars.get('confVal') as int xyz.newWriter().withWriter { writer -> writer << new groovy.json.JsonBuilder(request).toPrettyString() } 
  3. That's it, the value in the file should be replaced with what you have in the ${confVal} variable in the runtime.

More information:

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