j8d
j8d

Reputation: 510

Parsing nested elements from JSON response using a postman test script

I'm using the following Postman test script to check and log the status of a POST.

pm.environment.unset("uuid");
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
pm.test("Status code is 200",
    setTimeout(function() {
        console.log("Sleeping for 3 seconds before next request.");
        pm.sendRequest ( {
            url: url, 
            method: 'GET',
            header: {
                'account': account,
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8',
                'Authorization': auth
            }
        },
        function (err, res) {
            console.log(res.json().messageSummary);
        })
    },3000)
);

The script is able to make the call and retrieve the messageSummary from the response:

{
  "id": "3c99af22-ea07-4f5d-bfe8-74a6074af71e",
  "status": "SUCCESS",
  "token": null,
  "messageSummary": "[2] Records uploaded, please check errors/warnings and try again.",
  "data": [
    {
      "ErrorCode": "-553",
      "ErrorMessage": "Error during retrieving service service_id entered"
    }
  ]
}

I'm wanting to also get the nested ErrorMessage, but so far everything I've tried comes back undefined or throws an error.

I assumed console.log(res.json().data[1].ErrorMessage) would work, but, alas, it does not.

UPDATE: arrays start with [0] not [1]...

pm.environment.unset("uuid");
var jsonData = pm.response.json();
pm.environment.set("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
setTimeout(function() {
    console.log("Sleeping for 3 seconds before next request.");
    pm.sendRequest ( {
        url: url, 
        method: 'GET',
        header: {
            'account': account,
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
            'Authorization': auth
        }
    },
    function (err, res) {
        console.log(res.json().messageSummary);
        console.log(res.json().data[0].ErrorCode + ': ' + res.json().data[0].ErrorMessage)
    })
},3000)

Upvotes: 1

Views: 506

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25851

You would need to change the [1] to [0] to fix that reference.

Upvotes: 2

Related Questions