使用邮递员测试脚本从 JSON 响应中解析嵌套元素

Parsing nested elements from JSON response using a postman test script

我正在使用以下 Postman 测试脚本来检查和记录 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)
);

脚本能够进行调用并从响应中检索消息摘要:

{
  "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"
    }
  ]
}

我还想获取嵌套的 ErrorMessage,但到目前为止我尝试过的所有操作都未定义或抛出错误。

我以为 console.log(res.json().data[1].ErrorMessage) 会起作用,但是,唉,它不起作用。

更新:数组以 [0] 而非 [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)

您需要将 [1] 更改为 [0] 以修复该引用。