How to get nested variable set as global?

Hi There,

I’m trying to get the “id” value from the response I get into a global variable.

Now I’m told that the proper way to do this is to use this as a testscript:

let response = pm.response.json();
pm.globals.set("attachementid", response.id);

But the response is nested in the manner below and there may be multiple attachments (it’s a request that gives attachments and my next move is to use another request using the id (set properly as a global variable) to delete the attachments).

[
    {
        "id": "7296c158-a313-4b7b-b9bb-fc4bcc757dcf",
        "fileName": "Alex.txt",
        "downloadUrl": "/tas/api/incidents/id/5857f8e5-49ea-407a-b452-bfbcf737242d/attachments/7296c158-a313-4b7b-b9bb-fc4bcc757dcf/download",
        "size": 0,
        "description": null,
        "invisibleForCaller": false,
        "entryDate": "2020-06-18T13:16:13.000+0000",
        "operator": {
            "id": "f5ebc9f7-9dff-5af3-bb48-776ebb2e3734",
            "name": "Buzing, Alex"
        },
        "person": null
    },
    {
        "id": "f092d46c-8d17-4628-92de-7e268021f309",
        "fileName": "test.txt",
        "downloadUrl": "/tas/api/incidents/id/5857f8e5-49ea-407a-b452-bfbcf737242d/attachments/f092d46c-8d17-4628-92de-7e268021f309/download",
        "size": 0,
        "description": null,
        "invisibleForCaller": false,
        "entryDate": "2020-06-18T12:50:35.000+0000",
        "operator": {
            "id": "f5ebc9f7-9dff-5af3-bb48-776ebb2e3734",
            "name": "Buzing, Alex"
        },
        "person": null
    }
]

Maybe you could point me in the right direction?

Regards, Alex

Hey @PG_Alex

Welcome to the community! :rocket:

The response is an array which has a couple of objects within it. You would need to reference the object that you would like the id value from to set that as the variable.

For example, this would get the id from the first object:

pm.globals.set("attachementid", response[0].id); 

It’s zero-indexed so 0 would be the first one, 1 would be the second one…and so on.

Hope this helps! :smiley:

Hi Danny,

It sure did, it was exactly waht I was looking for!

Thanks for your elaborate reply.

Cheers, Alex

1 Like