Assertion for checking key name (array) in request body?

I have Request Body as below (Reality, I will request more than 100 key names ) and I want to check all key names requested are present or not? But I got a problem with handling array “errors” => Have any advice for me? Please help me. Thank you!

{
"user_id": 123,
"status": "completed",
"errors":[
        {
            "error_code": "E01",
            "error_message": "Wrong img"
        }
    ]
}

My assertion as below but it cannot check these key name: error_code, error_message are present and correct or not.
let requestBody = JSON.parse(pm.request.body);
pm.test(“Check keys of request body”, function () {
pm.expect(requestBody).to.have.keys([‘user_id’,‘status’,‘errors’]);
});

Hi @trangntt19hcm,

If you include this code within your test, it will loop through all of the items in the “errors” list, and check that these keys are present for every error. (If there are no errors present, the loop will be skipped.)

for (var i=0; i < requestBody.errors.length; i++) {
    pm.expect(requestBody.errors[i]).to.have.keys(['error_code','error_message']);    
}
1 Like

Thanks for your help,
May I ask you one more case?
My Request Body as below => I want to check whether all keys in request body (id, status, account/acc_code, account/acc_cate, account/acc_name, account/payment/pay_code, account/payment/pay_name, unit) are present or not? How do I should? Have any Arrsertion which support check all keys name presented at a time?

{
"id": 123,
"status": "completed",
"account":
        {
            "acc_code": "AC01",
            "acc_cate": 1,
			"acc_name":"ABC",
			"payment":
					{
						"pay_code":"PM01",
						"pay_name":"XYZ",
					}
		    .
			.
			.
			.
        },
"unit":
		{
			

		}
}

Currently, I have a solution as below => Is it correct? whether have an Arrsetion check all keys in a time? Have any advice for me?
let jsonReq = JSON.parse(pm.request.body);
pm.test("Test array L1", () => {
	pm.expect(jsonReq).to.have.keys(['id','account','unit']); 
}); 

pm.test("Test array L2", () => {
   for (var i=0; i < jsonReq.account.length; i++) {
    pm.expect(jsonReq.account[i]).to.have.keys(['acc_code','acc_cate','acc_name','payment']); 
}
}); 

pm.test("Test array L3", () => {
   for (var i=0; i < jsonReq.account.payment.length; i++) {
    pm.expect(jsonReq.account.payment[i]).to.have.keys(['pay_code','pay_name']); 
}
});