How to write a validation script for values contained in arrays

I have a response body and I want to check if the Errors received in the body has "rejectionErrorCode": "YYY".

Please find my response body below:

{
    "acknowledgement": {
        "messageHeader": {
            "testFlag": 0,
            "sourceMessageID": "TEST"
        },
        "messageType": "1",
        "status": "299",
        "primaryRepositoryID": "XXX",
        "Errors": [
            {
                "rejectionErrorCode": "YYY",
                "rejectionErrorDescription": "ZZZ",
                "rejectionErrorData": "AAA"
            }
        ]
    }
}

Hey @debjchak

Welcome to the community :wave:

This could be used as a test to check for that value:

pm.test("Response Value Check", () => {
    let jsonData = pm.response.json()
    pm.expect(jsonData.acknowledgement.Errors[0].rejectionErrorCode).to.equal("YYY");
});   

The main part that’s doing all the work to drill down through the response, to get to the value is jsonData.acknowledgement.Errors[0].rejectionErrorCode. Think of it as just stepping down through the JSON. For each of the keys, you’re taking a single step down.

The one important thing is that Errors is an array or a list of objects and you need to specify which item from the list you want.

In this case, it’s the first item so we reference this with a [0] as this is zero indexed.

We can then drop down a step into the first item, where we find the rejectionErrorCode property whose value we want to check.

We can assert against that property using the pm.expect() function.

pm.expect(jsonData.acknowledgement.Errors[0].rejectionErrorCode).to.equal("YYY")

If the Errors array had more than one object and you wanted to check each one, you will need to iterate through them.

This is one way that you could do that:

pm.test("Response Value Check", () => {
    let jsonData = pm.response.json().acknowledgement.Errors
    _.each(jsonData, (arrItem) => {
        pm.expect(arrItem.rejectionErrorCode).to.equal("YYY");
    })
});

Hope this all makes sense and helps you out. :slight_smile: