How can I set an environment variable using Tests from a nested array in Postman?

46 views Asked by At

Im brand new to Postman


 My Postman response is:

    [
        {
            "Item": {
            "CertificationExpirationDateType": 0,
            "CertificationExpirationAbsoluteDate": 0,
            "isExam": false,
            "CertificationExpirationRelativeDateOffset": 0,
            "CertificationExpirationSendInvitation": false,
            "CertificationExpirationTargetCourseId": 0,
            "CertificationExpirationTargetCurriculumId": 0,
            "ContentType": "test",
            "Description": "",
            "EnrollmentType": 1,
            "FolderId": 0,
            "PresentationId": 686183320}
    }]

I want to set an environmental variable called presentation_id to value of "PresentationId"

I tried this in TESTS tab

`

     var my_value = pm.response.json().Item[0].PresentationId
     pm.environment.set('presentation_id', my_value)

AND

`

    var Response = pm.response.json();
    pm.environment.set ("presentation_id",Response.Item.PresentationId);

AND I tried this

    `// get the response body
   var Response = JSON.parse(responseBody);
    // init counter
    var loop_count = 0

    for (count = 0; count < Response.Item; count++)
    {
        if (Response.Item[count].PresentationId == "0")
       {
            var presentation_id = Response.Item[count].PresentationId;
             postman.setEnvironmentalVariable("presentation_id", PresentationId);
       }
    }`

I was expecting the variable in my Environment to be 686183320 but it is coming back null

1

There are 1 answers

0
Danny Dainton On

The response is an array with a single object so you would need to place the [0] at that point and not on .Item.

let my_value = pm.response.json()[0].Item.PresentationId
pm.environment.set('presentation_id', my_value);