Skip array element if variable blank\null in CSV

Hi, I’m trying to create a test to run in the Collection Runner with a CSV file to set the input variables.
The request is a POST with an array that can contain up to 3 values.

"Array1": [
    {
        "Id": {{var1}}
    },
    {
        "Id": {{var2}}
    },
    {
        "Id": {{var3}}
    }    ]

If var2 or var3 are not specified in a particular row of the CSV file, I need the request to omit that element from the array for that iteration. Is this possible?

Thanks!

@nmasson-pbc

I haven’t actually tried this but in theory it should work …

For the POST body …

"Array1": [ {{postVars}} ]

I don’t know what your actual CSV vars are but this is what would go into “Pre-req” …

var var_1 = pm.iterationData.get("var1");
var var_2 = pm.iterationData.get("var2");
var var_3 = pm.iterationData.get("var3");

var postVars = '{ "Id": "' + var1 + '" }';

if ( var_2 !== '' ) {
    postVars = postVars + ',{ "Id": "' + var_2 + '" }';
}
if ( var_3 !== '' ) {
    postVars = postVars + ',{ "Id": "' + var_3 + '" }';
}

Like I said above, I haven’t actually run this but you could try it and tweak it if needed.

2 Likes

This solved my issue, thanks so much for your help!

How did you solved it?

Anyone who looking for an answer for this question can follow this gist:

Just copy and paste the code to the prerequest section in request