POSTMAN : parsing a JSON response, how deep can I

2019-09-14 23:23发布

问题:

I'm currently trying to parse precisely a JSON response (using POSTMAN).

The JSON response has the following structure (I use ... to skip irrelevant info):

*

{
  "href": ...,
  "offset": ...,
  "limit": ...,
  "first": ...,
  "last": ...,
  "entries": [
    {
      "href": ...,
      "id": ...,
      "name": "MY_FIRST_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    {
      "href": ...,
      "id": ...,
      "name": "MY_SECOND_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    ...
    ]
}*

I want to test several known values: tests["test first item"] = responseBody.has("MY_FIRST_ITEM_NAME") this works, but I also want to check the associated device type if I use responseBody.has("MY_ITEM_TYPE") I can't figure out to which item it is related to, so I try to make a more precise checking: *

tests["test entries 0"] = body.entries[0].name === "MY_FIRST_ITEM_NAME"*; 
this works but when it comes to test the device type:
tests["test entries 0"] = body.entries[0].attributes.device.type

it ends up with an error "TypeError: Cannot read property 'type' of undefined"

With the console I can see the attributes (doing console.log(body.entries[0].attributes);) but it is not possible to go one step deeper. Is it a postman limitation ? is there another way to reach precisely this device.type information ?

Thank you for help

Alexandre

回答1:

Oups ! sorry for the edit, I'm quite new to this. Here is the answer for this problem, The device.type attribute can be reached this way: body.entries[0].attributes['device.type']

There are some limitations though: - I can't use .attributes[2], 2 being the index of the element if 'attributes' could be seen as a table. - The syntax is particular, it doesn't work if we use double-quotes instead of single-quotes - I still don't know why it happens at this stage ... if someone knows, I'll be happy to read from him

Cheers

Alexandre