Null Variables in Body of a Put

I am trying to use a variable that has a null value in the body of a PUT. The null gets converted to “” after the post. Is there a way to have variable actually set the field null instead of an empty string?

pm.collectionVariables.set("Address1", "21 Lake Dr.");
pm.collectionVariables.set("Address2", null);
pm.collectionVariables.set("City", "Saint Louis");
pm.collectionVariables.set("State", "MO");
pm.collectionVariables.set("ZipCode", "63123");

PUT .../api/address/{id}

{
   "id": "1",
   "Address1": "{{Address1}}",
   "Address2": "{{Address2}}",
   "City": "{{City}}",
   "State": "{{State}}",
   "ZipCode": "{{ZipCode}}"
}
1 Like

Hey @ewstoces,

Welcome to the community! :wave:

You could do something like this to add the null value.

Add the dynamic variable to the request body without quotes:

{
	"Address2": {{Address2}}
}  

In your Pre-request Script, add the null value with quotes:

pm.collectionVariables.set("Address2", "null");

This is would it look like in the response body, I’m just using the postman-echo service to replicate the request:

1 Like

thank you so much, I had the exact opposite issue… my variable was null and it was a required value so the POST was failing. but “null” with the double quotes works perfect.

such a simple solution, thanks!

Hi, I have similar issue but only when the data is read from CSV.

It’s undefined in CSV file so I’m converting it to null to pass it to JSON.

for(var key in data){
if(data[key] == ‘’){
data[key] = JSON.stringify(null);
}
}

But when I’m reading it in the Body as below:
“isDelta”: {{isDelta}} (Here Is Delta is part of the CSV Header)

It still comes as undefined. i.e. “isDelta”: , instead of “isDelta”:null,. The whole structure inside the body is JSON.

@maulikdoshi82

Data should be a object that represents the current line in the CSV file, but I’m not sure you can change the element values in the object in a pre-request script. It’s a special variable. I don’t know if its read only or not.

I have just tested it. I can overwrite the data in the pre-request tab and console log it which shows the changes.

However, if I console log the data element in the tests tab, it hasn’t changed and if I add the variables to the body, they are taking the initial data from the CSV file, not the updated values.

So it looks like when you update the object in the pre-request script, the scope only applied to the pre-request script.

It looks like you will need to create a new environment\collection variable, and consume that instead. (Like the example provided by Danny).

Or put in a bug\feature request to get Postman to deal with the null values correctly (as they are valid JSON value type).