0
votes

I am trying to parse a JSON response from Postman that is not cooperating. Here is the body response:

    {
    "teams": [
        {
            "id": "MI6",
            "name": "James Bond's Workspace",
            "color": "#04a9f4",
            "avatar": null,
            "members": [
                {
                    "user": {
                        "id": 007,
                        "username": "James Bond",
                        "email": "[email protected]",
                        "color": "#e65100",
                        "profilePicture": null,
                        "initials": "JB",
                        "role": 1,
                        "custom_role": null,
                        "last_active": "1609978205632",
                        "date_joined": "1609897014429",
                        "date_invited": "1609897014429"
                    }
                }
            ]
        }
    ]
}

I am using the following test scripts that can't seem to resolve the [ value after teams.

var jsonData = JSON.parse(responseBody);

postman.setEnvironmentVariable("teams_id", jsonData.teams.id);

postman.setEnvironmentVariable("teams_id", jsonData.teams.user.id);

It is creating the variable for me, but will not store the value of MI6 or the value of 007.

2
007 as per your response is a numnber 007 is not valid number , what error is thrown in postman could you add that - PDHide

2 Answers

0
votes

You're trying to access values that are in an object, inside an array.

Specifying the object you need with [0] because it's the first object in the array, will get the value. You would also need to do the same with members.

This should be what you need:

var jsonData = pm.response.json();

pm.environment.set("teams_id", jsonData.teams[0].id);

pm.environment.set("user_id", jsonData.teams[0].members[0].user.id);
0
votes

Danny thanks for your response. I found another thread about parsing json data from an array and used this response to fix the issue. Here is what worked:

var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.teams.length; i++) {
    var teams_id = jsonData.teams[i];
    console.log(teams_id.id);
    console.log(teams_id.name);
    postman.setEnvironmentVariable ("teams_id",teams_id.id)
    postman.setEnvironmentVariable ("teams_name",teams_id.name)
}