Getting Childs of a non Array JSON

Hi there,

I am currently struggling to get a Child Item with variable Name from a JSON.

It looks like this:

{
    "Layer1a": [],
    "Layer1b": {
        "Layer2a-5cdabbbc7c0f4d89ad788ad88e6d061d": {
            "Layer3": {
                "Layer4": "SomethingFancy-f2417a52e4f84c299564d571b3947a2b"
            }
        },
        "Layer2b-5cdabbbc7c0asdfasdfasfasfdsadfasdf": {
            "Layer3": {
                "Layer4": "SomethingFancy-f2417a52e4f84c299564d571b3947a2b"
            }
        }
    }
}

I normally would access Layer2b as an Array with pm.response.json().Layer1b[0]

But as it is not an Array i just get undefined.

Does Someone got an Idea how to solve this?

It’s just a set of objects so you can work down through this with dot/bracket notation:

pm.response.json().Layer1b["Layer2a-5cdabbbc7c0f4d89ad788ad88e6d061d"].Layer3.Layer4

The reference to this key Layer2a-5cdabbbc7c0f4d89ad788ad88e6d061d would need to be made using bracket notation as it contains the - character.

Yes that works, however i do not know the second part of Layer2a as it is a random generated GUID.
That is basically my core problem.

Normally i get the json as array and can navigate through it with pm.response.json().Layer1b[0] so i totally got around using the Name at all.

So for using your approach i would need to use some wildcard characters like:
pm.response.json().Layer1b[“Layer2a*”]

So i came up with a solution. Its not pretty but it works.
I hope someone has a better idea.

var response_txt = pm.response.text();
var pos = response_txt.indexOf("Layer2a-");
pos = pos+8;
var guid = response_txt.substring(pos, pos+32);
console.log(pm.response.json().Layer1b["Layer2a-" + guid]);

You could also use something like this:

let objectKeys = _.keys(pm.response.json().Layer1b)

_.each(objectKeys, (key) => {
    console.log(pm.response.json().Layer1b[key])
})

This will get all the keys from the Layer1b object, without having to worry about the value. As that creates an array of those keys, you can loop through each one and log out the objects within them to the console.

It’s using the built-in Lodash module to get the keys and loop through them.