javascriptpostmanpostman-pre-request-script

Extract value of a dynamic key from response


I have a response as below:

{
    "value": {
        "element-6066-11e4-a52e-4f735466cecf": "b721a18e-ffab-49bc-acdf-5a30c84e160d"
    }
}

I want to extract the value of they dynamic key labelled "element-6066-xxxx-xxxx-xxxxxxxxx" (changes each time I re-run the API call).

Any guidance would be greatly appreciated.

I tried the following:

var data = JSON.parse(responseBody);
pm.environment.set("elementId", Object.keys(data.value)[0]);

But this sets the "key" instead of the "value" (expecting 'b721a18e-ffab-49bc-acdf-5a30c84e160d' to be set.


Solution

  • You would need to use Object.values() for this:

    let res = pm.response.json();
    pm.environment.set("elementId", Object.values(res.value)[0]);