JSON Test in the response body when without variable name in array followed by nameless object

I am trying to write a test case to pull out the first object in an array that is nameless followed by objects that are arrays.

Trying to pull “this-one” for the first object in the array.

The body looks like this:

[
    { 
        "a": "data", 
        "this-one": 9999 
    }, 
    { 
        "a": "data", 
        "this-one": 12234 
    }
]

The test snippet I am trying to adapt from “Response Body: JSON value check”.

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.**value**).to.eql(9999)

I am having trouble figuring out what to put after jsonData.___________

This should work:

pm.expect(jsonData[0]["this-one"]).to.eql(9999)

The response is an array, which contains objects so in order to access them you need to specify which object you want using [0] - Then it’s just a case of adding the key to the value you need.

1 Like

Hey @danny-dainton

I have the same situation as above, but when I tried your solution, but its giving me error.

For more clarity:
Response Body:

[
 {
   "id": "U123",
   "code": "Wallet"
},
{
  "id": "U124",
  "code": "GoogleWallet"
},
{
   "id": "U125",
  "code": "AppleWallet"
}
]

So wrote the query as :

pm.test("Apple Wallet Feature is retrieved with success.", function(){
    pm.expect(jsonData[2][code]).to.eql("AppleWallet");
});

But it fails with this error: ReferenceError: code is not defined

Hey :wave:

As this reply is 3 years later, could you provide more context about your specific usecase please?

What’s the full script you’re using?

Are you saving the full response into the same jsonData variable?

Sure… I can imagine lot has changed in 3 years.

Here is the full script which I was trying.

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

let jsonData = JSON.parse(responseBody);

pm.test("Apple Wallet Feature is retrived with success.", function(){
    pm.expect(jsonData.items).to.have.length>2;
    pm.expect(jsonData[2][code]).to.eql("AppleWallet");
});

What do you see logged in the console when you use console.log(pm.response.json())

The script should probably be more like:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

let jsonData = pm.response.json();

pm.test("Apple Wallet Feature is retrived with success.", function(){
    pm.expect(jsonData.length).to.be.above(2);
    pm.expect(jsonData[2].code).to.eql("AppleWallet");
});

Are those assertions not going to break if there are more objects pushed to that array?

The latest solution worked.

I will be filtering the API call with Odata, hence the “AppleWallet” is always in 3rd place. So it should not break the assertion when more objects are pushed.

Thanks for helping.

1 Like