Анализ вложенных элементов из ответа JSON с использованием тестового скрипта почтальона

Я использую следующий тестовый скрипт 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)
);

Сценарий может сделать вызов и получить messageSummary из ответа:

{
  "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)

person j8d    schedule 20.02.2020    source источник
comment
Не будет ли [0] вместо [1]?   -  person Danny Dainton    schedule 20.02.2020
comment
В вашем сценарии также много смешанного синтаксиса между старым и новым. pm.response.json() вместо JSON.parse(responseBody) и pm.environment.set() вместо postman.setEnvironmentVariable(). Кроме того, вы завернули pm.sendRequest() без всякой причины, на самом деле это не противоречит чему-либо, как я вижу ????   -  person Danny Dainton    schedule 20.02.2020
comment
Спасибо Дэнни. Да, это будет [0] вместо [1].   -  person j8d    schedule 20.02.2020


Ответы (1)


Вам нужно будет изменить [1] на [0], чтобы исправить эту ссылку.

person Danny Dainton    schedule 20.02.2020