20

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

2 Answers 2

32

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Great. Works like a charm :)
@UrošKočevar, I think you should accept it as the answer.
2

Use if on loop for find value from array object. I try it and it work.

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

2 Comments

I was looking something like this i wonder if can execute a request for each value extracted from the array?
for(const item of jsonData) { /* use item here in loop */ }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.