How can I pick random element from my response and keep as collection variable?

Hi. I want to keep a collection variable from my response randomly in order to use it in the next request in the same folder.
I need to pick "id"s randomly as collection variables. How can I do that ? Thank you in advance.

Here is my response:
{
“status”: “success”,
“response”: [

    {
        "id": "5cbda77e82ba2c38f751a6ff",
        "preview_url": "https://picture.jpg",
        "width": 1024,
        "height": 576,
        "license": "gold"
    },
    {
        "id": "5c4b24be9785183d57985cf7",
        "preview_url": "https://picture.jpg",
        "width": 1536,
        "height": 1024,
        "license": "gold"
    },
    {
        "id": "5c485d30d34c7850aa821275",
        "preview_url": "https://picture.jpg",
        "width": 1536,
        "height": 1024,
        "license": "gold"
    },
    {
        "id": "5bd9b971b7e954523088ab30",
        "preview_url": "https://picture.jpg",
        "width": 1024,
        "height": 1024,
        "license": "gold"
    },
    {
        "id": "5c780d855afbc36ee0801727",
        "preview_url": "https://picture.jpg",
        "width": 1024,
        "height": 1280,
        "license": "gold"
    }
],
"metadata": {
    "next_page": "https://sitenext804859084395304750734058904830958.com"
}

}

Do you want to save the entrie ids and then randomly use any one of it in the next request or you just want to save any one of it randomly?

If you want to save all the Id values just use ._each function .

I want to save any of these ids randomly and use it in the next request.
Could you please give me an example?

Can anyone help me please?:frowning:

I do this in a handful of my collections. It’s not too bad. Add this snippet in the tests section of your request:

 const jsonData = pm.response.json();
 const index = Math.trunc(Math.random() * jsonData.response.length);
 const item = jsonData.response[index];

 pm.collectionVariables.set("test-itemId", item.id);
1 Like

New one on me collectionVariables, but nice clean solution to the problem.

Then just refer to {{test-itemId}} in the next request Anna.

1 Like

I also do something similar, but as a test set these as an environment variable and in the last request in collection unset these

pm.test("Set AccountId for the file upload, download and delete collection", function () {
    var AccountId = (pm.response.text().split(",")[0].split(":")[1].replace(/\"/g, ""));
    pm.environment.set("accountid", AccountId);
    //console.log(AccountId)
});

pm.test("Unset the environment variables for accountId and account_fileId", function () {
    pm.environment.unset("accountid");
    pm.environment.unset("account_fileId");
});