I have a csv file like below. Where in row1 all the headers value are passed and in the 2nd row countryId is null since it optional.
userName,password,address1,countryId
test1,pass1,lblr,1
test2,pass2,
When i read the csv file in postman pre-request i am getting output as below.
userName: "roxxroyce"
password: "Pass@123"
address1: "LBLR"
countryId: 1
userName: "roxxroyce"
password: "Pass@123"
address1: "RQIP"
Tried the below code login to achieve the expected output. But this seems to be not giving the correct results. Can someone help me with this request?
let lines = iterationData.split('\n');
let headers = lines[0].split(',');
let requestBodyArray = [];
for (let i = 1; i < lines.length; i++) {
let values = lines[i].split(',');
let userObject = { user: {} };
for (let j = 0; j < headers.length && j < values.length; j++) {
let key = headers[j].trim();
let value = values[j] ? values[j].trim() : ''; // Check if value exists before trimming
if (value !== "") {
if (key === "countryId") {
// Add countryId to the address object
if (!userObject.user.address) {
userObject.user.address = [{ [key]: value }];
} else {
userObject.user.address[0][key] = value;
}
} else if (key === "address1") {
// Add address1 to the address object
if (!userObject.user.address) {
userObject.user.address = [{ [key]: value }];
} else {
userObject.user.address[0][key] = value;
}
} else {
// Add other properties to the user object
userObject.user[key] = value;
}
}
}
requestBodyArray.push(userObject);
}
// Log the resulting request body
console.log(JSON.stringify(requestBodyArray, null, 2));
Expected output:
iteration#1:
{
"user": {
"userName": "test1",
"password": "pass1",
"address": [
{
"address1": "lblr",
"countryId": "1"
}
]
}
}
iteration#2:
{
"user": {
"userName": "test2",
"password": "pass2"
}
}