I have the following JSON. My goal is to post parameter with value of ""(empty string) if empty string is provided, and to remove parameter from the call if some predefined string, like "nullValue" is provided.
{
"Name": "Some Name",
"AddressLine1": "1st Str.",
"BuyerIdentifier": "nullValue",
}
I've looked at several questions, but non of PreProcessor solutions offered there worked for me. Mostly they offer removeArgument() method.
for (Iterator iterator = sampler.getArguments().iterator();){
prop = iterator.next();
String value = prop.getStringValue();
if (value == "nullValue") {
sampler.removeArgument(prop.getName());
}
}
I ran below
sampler.getArguments().getArgumentCount()
And it returns "1", so the whole JSON is returned as one argument. So I can't delete individual argument. Thanks.
Put the following code into "Script" area:
def oldRequest = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
oldRequest.values().removeAll{it.equals('nullValue')}
def newRequest = new groovy.json.JsonOutput().toJson(oldRequest)
sampler.getArguments().removeAllArguments()
sampler.setPostBodyRaw(true)
sampler.addNonEncodedArgument('',new groovy.json.JsonOutput().prettyPrint(newRequest),'')
Assuming your payload is valid JSON the PreProcessor will remove all JSON elements having nullValue
as value.
More information: