0

Trying to parse this JSON response and get the id Value

{
    "responseStatus": "SUCCESS",
    "size": 1,
    "start": 0,
    "limit": 200,
    "documents": [
        {
            "document": {
                "id": 26,

Using this script to parse the response and post the value as an environment variable, for some reason is not retrieving the expected response.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData.id);

Although it created the id variable in the environment, the value is empty.

  • Possible duplicate of [*How can I access and process nested objects, arrays or JSON?*](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – T.J. Crowder Nov 15 '19 at 14:11
  • try -- var data = pm.response.json(); pm.environment.set("id", data.documents[0].document.id); – ecstatic Nov 15 '19 at 14:11
  • The `id` property isn't on the outermost object, it's on `.documents[0].document`. So: `postman.setEnvironmentVariable("id", jsonData.documents[0].document.id);` – T.J. Crowder Nov 15 '19 at 14:12
  • 1
    Thank you @T.J.Crowder. It works – Vlad Haidan Nov 15 '19 at 15:59
  • @VladHaidan - No worries! Glad that helped. FWIW, I suggest just deleting the question, since it won't be of use to others in the future (we have [this one](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) for that). Happy coding! – T.J. Crowder Nov 15 '19 at 16:02

1 Answers1

1

Since the id is under an object in the documents array of the response, you should use this

var jsonData = JSON.parse(responseBody);
var id = jsonData.documents[0].document.id;
postman.setEnvironmentVariable("id", id);
Kwame Opare Asiedu
  • 2,110
  • 11
  • 13
  • Also, you're missing out part of the path to the value. It's really best not to post an *answer* to this kind of question. It's effectively a typo and/or duplicate. – T.J. Crowder Nov 15 '19 at 14:13