Help with JSON extraction

Hi.

I am doing my first steps towards an “advanced” use of Postman. I am trying to extract data from a JSON response. The JSON response looks like:

{
    "args": {},
    "headers": {
        "x-forwarded-proto": "https",
        "host": "postman-echo.com",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate",
        "cache-control": "no-cache",
        "cookie": "sails.sid=s%3AgX-JxoOgGc7tWEb8jw_6YBH5VKcxH8R8.M7J38uMcN090VYnxRHu6eF4rkq7arAemQXhfRd9TWz4",
        "postman-token": "b5ef1d87-d4fc-4ec4-b961-6a412a06a0d1",
        "user-agent": "PostmanRuntime/7.11.0",
        "x-forwarded-port": "80"
    },
    "url": "https://postman-echo.com/get"
}

when I try something like

var data = pm.response.json();
pm.environment.set("host", data.headers.host);

It works perfectly. If however I add

pm.environment.set("responseToken", data.headers.postman-token);

I have an error:

ReferenceError | token is not defined

I imagine this has to do with the “-” character in the field name.

Can anyone help me? Thanks!!!

Hey @giuseppe.lacagnina,

Welcome to the community! :slight_smile:

So you should be able to wrap that in brackets to get the value from that key.

pm.environment.set("responseToken", data.headers['postman-token'])

As it has the - character in the key you would need to use the bracket notation rather than the dot notation.

Some more information on the different notation methods can be found here:

1 Like

Thanks a lot, it worked!!! All the examples around do not contemplate such cases.

1 Like

You’re welcome!! Glad it worked for you!! :trophy: