0

I'm trying to parse the value of "id" from the JSON body response to include in an environmental variable in Postman with no success. Here is an example of the Body response.

"payload": {
    "transaction": {
        "amount": "1.00",
        "id": "114255633",
        "type": "AUTH",
        "result": "APPROVED",
        "card": "XXXXXXXXXXXX1111",
        "authorization-code": "TAS977",
    }
}

and here is my script in postman

var jsonData = JSON.parse(responseBody);
var id = jsonData.payload[0].transaction.id;
postman.setEnvironmentVariable("id", id);

Any help would be appreciated. I think my error is in the way the value I'm looking to get is nested inside an array.

2 Answers2

4

postman provides inbuild method to retrieve json object you don't have to parse it:

Also use the new pm api instead postman

pm.environment.set("id", pm.response.json().payload.transaction.id);
PDHide
  • 18,113
  • 2
  • 31
  • 46
  • 2
    For more information: https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/ – Danny Dainton Apr 07 '21 at 07:31
0

If I am not wrong..This should work

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData["payload"]["transaction"]["id"]);
Kartikey
  • 4,516
  • 4
  • 15
  • 40
  • 1
    i thought this too originally. Postman keeps throwing TypeError: Cannot read property 'id' of undefined – Robert Cowie Apr 06 '21 at 19:00
  • 1
    Try this `var jsonData = JSON.parse(responseBody); postman.setEnvironmentVariable("id", jsonData["payload"]["transaction"]["id"]);` – Kartikey Apr 06 '21 at 19:02
  • individualizing the objects did the trick. so simple! thanks! – Robert Cowie Apr 06 '21 at 19:05
  • The only thing wrong with your code would have been `payload[0]`, should just be `payload`. It's not an array so you don't need the `[0]`. I would also advise against using the older syntax and look to use the `pm.*` API in the sandbox now, the auto suggestion will show you this in the app. – Danny Dainton Apr 06 '21 at 20:58