Search code examples
jsonenvironment-variablespostman

Extract value from array of objects in Postman


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

Solution

  • 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);