-2

This is the response from Postman:

{
    "data": [
        {
            "firstname": "tahaq",
            "lastname": "postmanq",
            "accountenabled": "true",
            "email": "tahaiq@hotmail.com",
            "phoneactive": true,
            "phonenumber": "+18738021112",
            "brandname": "kwikset",
            "emailnotification": true,
            "smsnotification": true,
            "pushnotification": true
        }
    ],
    "total": 1
}

Test in postman I am using:

let jsonData = JSON.parse(responseBody);
pm.test("Verify firstname", function () { 
    pm.expect(jsonData.firstname).is.to.equal("tahaq"); 
});

Error return as:

Verify firstname | AssertionError: expected undefined to equal 'tahaq'
1

Just to add to the above answer , in JSON {} is a JSON object and [] is an Json array.

So the JSON.parse just parses the response string into proper JSON. As the response starts with a {} you can access elements inside it as key-value.

hence , jsonData.data will give content inside 'data' field. But now to access content inside data you have to use index as data is json array [].

And as there is only one json object {} in the array, use jsonData.data[0] means, the first JSON object in the jsonArray. Now again we have a jsonObject , so to get the field "firstname" we use:

jsonData.data[0].firstname

When ever you are in doubt in postman just print the content using console.log.

so just print :

let jsonData = JSON.parse(responseBody);
console.log(jsonData);

The console output could be viewed in postman console which is under view> show postman console (or by pressing alt+ctrl+c) :

enter image description here

When you print it , you can JSON.parse prints the same response body :

enter image description here

so here we can see the structure like data>[0]>firstname:

| improve this answer | |
0

The problem is with this: pm.expect(jsonData.firstname).

You left out data which is an array, so you need to write: pm.expect(jsonData.data[0].firstname) in order to find firstname in your json.

| improve this answer | |
0

you have an array, so do this

let jsonData = JSON.parse(responseBody);
pm.test("Verify firstname", function () { 
    pm.expect(jsonData[0].firstname).is.to.equal("tahaq"); 
});
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.