Body matches string validations for array of Objects

I have a response in below format.

[
    {
        "Name": "PQR",
        "Code": "000XXY",
        "Text": "ssdd1",
        "Charg1": {
            "step": 1,
            "Months": 3,
            "endDate": "2099-09-01T00:00:00",
            "percent": 10
        },
        "Fees1": false
    },
    {
        "Name": "ABC",
        "Code": "000XXY",
        "Text": "assd2 ",
        "Charg2": {
            "step": 2,
            "Months": 3,
            "endDate": "2099-09-01T00:00:00",
            "percent": 10
        },
        "Fees2": false
    },
]

I have tried below test scripts to validate the objects using below functions

var jsonData = JSON.parse(responseBody);
console.log(jsonData.length);

     pm.test("Body matches string from response body",function()
    {   
        for (i=0; i<jsonData.length;i++)
        {
            pm.expect(jsonData[i].text).to.include("Name");
        }

    });

Getting Below error message

Body matches string from response body | AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given

Hey @sudarshan.ohal

Welcome to the Postman community! :star:

I’m not 100% clear what you’re trying to check for but it looks like you’re trying to check that the Name property is part of each object.

You could do that like this:

pm.test("Body matches string from response body", function() {   
	for (i=0; i < jsonData.length; i++) {
		pm.expect(jsonData[i]).to.have.property("Name");
	}
});

The reference with had in the pm.expect() statement jsonData[i].text, doesn’t exist in the object so it would be undefined.

This assertion would be looking for the property in the object called text and checking that the value of that included the string Name.

pm.expect(jsonData[i].text).to.include("Name");

@dannydainton: Thanks for the quick help. This is working for me.

1 Like