How to count length of response in new syntax

I am struggling with the new syntax and would need your input. How can you write below test with pm? (the new syntax)

responseJson = JSON.parse(responseBody);
tests["Nr of plans returned = " +responseJson.length] = responseJson.length === 2;

I appreciate your help!

Hey @captain_hoy, here’s how you can achieve what you want with the new pm.* syntax.

var data = pm.response.json();

pm.test('Number of plans returned = ' + data.length, function () {
    pm.expect(data.length).to.equal(2);
});

In case you want to check the count of keys in a JSON object, simply replace data with Object.keys(data) and you’ll be good to go.

Also, you can access the complete API reference here in case you would like to check it out. Hope this helps.

8 Likes

@deepak.pathania thank you

hi, how can i get the count and name of the response body in API POSTMAN ,PLEASE GIVE ME A SUGGESTION.

new to this syntax, what about if the json had no root, how do you use the Json as Json Array length: pm.test(Count: ${pm.response.json().length}) seems to only look at the entire json?

Json response without root:

[
    {
        "id": "1"
    },{
        "id": "2"
    }
]

Hello Deepak

I am trying to get the number of keys in the response body.

You wrote:

In case you want to check the count of keys in a JSON object, simply replace data with Object.keys(data) and you’ll be good to go.

I am not clear about this. I tried:

const responseJson = pm.response.json();

console.log("The number of expected keys in the response body is: " + Object.keys(data));

That does not work.

What am I doing wrong?

Thanks
Phil

Hello @starPilot Welcome to the Community :bouquet:

In the above example he is storing the parsed response under the variable “data”

in your case it should be

const responseJson = pm.response.json();

var count = Object.keys(responseJson).length;

console.log("The number of expected keys in the response body is: " + count);

Please let me know if this works:-)

You could also use Lodash to find that length:

console.log(`Number of keys: ${_.size(pm.response.json())}`)

https://lodash.com/docs/4.17.15#size

1 Like

Works great!

Thank you

StarPilot

1 Like

Here’s a collection demonstrating how you can either count the length of an array, or count the number of keys in a specified array:

https://www.postman.com/postman/workspace/postman-answers/collection/9215231-6d1bb03a-5a0a-4ec4-ab9c-d79c01ac96d7?ctx=documentation

Fork it and try it out!

1 Like