I have a array object in json response in which i want to loop through isRetail parameter and set the id to global variable if the condition is met. Sample JSON response:
{
"status": 200,
"data": {
"users": [
{
"id": 95,
"isRetail": true
},
{
"id": 118,
"isRetail": false
}
],
"pagination": {
"pageNumber": 1,
"pageSize": 25,
"totalCount": 2,
"totalPages": 1,
"isFirst": true,
"isLast": true,
"totalCountOnPage": 2
}
}
}
Here is my current test code that doesn't work but more or less what I'm working towards.
res=pm.response.json()
let users_len = res.data.users.length
for(let i= 0; i <= users_len; i++){
is_retail = res.data.users[i].isRetail;
if(is_retail == "true"){
pm.globals.set("UserId",res.data.users[i].id);
}else if (is_retail == "false"){
pm.globals.set("orgUserId",res.data.users[i].id);
}
}
I am getting the below error while executing the script.
TypeError: Cannot read properties of undefined (reading 'isRetail')
Can anyone help me with this issue?
res = pm.response.json();
let users_len = res.data.users.length;
for (let i = 0; i < users_len; i++) {
let is_retail = res.data.users[i].isRetail;
if (is_retail === true) { // Comparing with boolean true, not the string "true"
pm.globals.set("UserId", res.data.users[i].id);
} else if (is_retail === false) { // Comparing with boolean false, not the string "false"
pm.globals.set("orgUserId", res.data.users[i].id);
}
}
Here are the changes made to the code:
By making these modifications, the code should now correctly access the isRetail property and set the corresponding global variables based on the boolean values.