Search code examples
javascriptarrayspostman

How to iterate through postman JSON response and store it to global variable based on if else condition is met?


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?


Solution

  • 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:

    • In the for loop, the condition i <= users_len has been changed to i < users_len. This ensures that the loop iterates only up to the last index of the users array.
    • The variable is_retail is declared with the let keyword to avoid any scope-related issues.
    • The conditions in the if statements now compare is_retail with the boolean values true and false, respectively, instead of comparing with the strings "true" and "false". This aligns with the JSON structure where isRetail is a boolean value.

    By making these modifications, the code should now correctly access the isRetail property and set the corresponding global variables based on the boolean values.