Extract value from array of objects in Postman

久未见 提交于 2021-02-06 08:59:09

问题


I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);

JSON response:

[
  {
    "Id": 1287,
    "LastName": "Trump",
    "FirstName": "Donald",
    "MiddleName": "Von",
    "City": "New York City",
    "Phone": "66 77 88",
    "State": "New York",
    "Fax": "111-222-333",
    "ReferenceId": "12345",
    "Active": false,
    "CurrentWorkingSchemeId": null
  }
]

回答1:


If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:

var data = JSON.parse(responseBody);   
postman.setEnvironmentVariable("userid", data[0].Id);



回答2:


This works like charm! Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.

var jsonData = JSON.parse(responseBody);
    for (var i = 0; i < jsonData.data.length; i++) `
    {
    var counter = jsonData.data[i];
    postman.setEnvironmentVariable("schID", counter.id);
    }


来源:https://stackoverflow.com/questions/42257293/extract-value-from-array-of-objects-in-postman

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!