Search code examples
jmeterbeanshelljsr223

Jmeter trim whitespaces from a JSON File


I have the follow Json:

{
      "tipopersona": "M",
      "regimen": "36",
      "periodicidad": "Y",
      "ejercicio": "2020",
      "periodo": "035",
      "periodoDesc": "Del Ejercicio",
      "tipoDeclaracion": "001",
      "tipoDeclaracionDesc": "Normal",
      "tipoComplementaria": "",
      "tipoComplementariaDesc": "",
      "cmbISSIF": "1",
      "obligaciones": [ "0101", "0192" ],
      "preguntasPerfil": { "178": "1" },
      "rfc": "AAC920317CM8",
      "rechazopropuesta": false,
      "fechaVencimiento": "2021-03-31T00:00:00",
      "errores": true,
      "xmldeclaracion": ""
    }

I need to remove the blanks and newlines from the Json like the following example in JSR223 or Beanshell:

{"tipopersona":"M","regimen":"36","periodicidad":"Y","ejercicio":"2020","periodo":"035","periodoDesc":"DelEjercicio","tipoDeclaracion":"001","tipoDeclaracionDesc":"Normal","tipoComplementaria":"","tipoComplementariaDesc":"","cmbISSIF":"1","obligaciones":["0101","0192"],"preguntasPerfil":{"178":"1"},"rfc":"AAC920317CM8","rechazopropuesta":false,"fechaVencimiento":"2021-03-31T00:00:00","errores":true,"xmldeclaracion":""}

I'm using the follow code:

String data = vars.get("json");
data = data.replaceAll(" ", "");
data = data.replaceAll(System.getProperty("line.separator"),"");
vars.put("data", data);

But in the Debug Sampler it still shows the spaces:

enter image description here


Solution

    1. Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting
    2. Groovy has built-in JSON support

    Assuming above points you can achieve your goal using the following one-liner:

    vars.put('data', (new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parseText(vars.get('json'))).toString()))
    

    More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It