Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the length of json returned using Postman?

I send a request which sends me back something like:

{
    "items": [
        {
            "id": 86154,
            ...
        },
        {
            "id": 86194,
            ...
        }
}

I would like to count the size of this array in Postman test section. So I wrote:

var body = JSON.parse(pm.response.json());
tests["Count: "  + body.items] = true;

enter image description here

As you can see above, it didn't worked. I am new to both PostMan and Javascript, that's probably why.

like image 737
Revolucion for Monica Avatar asked Sep 06 '25 03:09

Revolucion for Monica


2 Answers

Simple answer is to get the same thing, using the new pm.* API syntax:

pm.test(`Count: ${pm.response.json().items.length}`)

The syntax you used is incorrect JSON.parse(pm.response.json()) - You can just use pm.response.json() and drop the JSON.parse().

To get the number of objects, you just need to use the .length property.

I'm not sure what you are testing for but this simple test would check or assert that you have 2 objects (Like your example) in the array:

let body = pm.response.json()
pm.test("Check the Items array length", () => {
    pm.expect(body.items.length).to.equal(2)
})

This is using the newer pm.test() syntax, more about this and all the other pm.* API methods can be found here:

https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/

If you just wanted to log out the value and not add that to a test, you can use console.log(pm.response.json().items.length) in the Tests tab and see this displayed in the Postman Console.

like image 71
Danny Dainton Avatar answered Sep 07 '25 21:09

Danny Dainton


.json() returns an promise. try it like this:

(async () => {
   var body = await pm.response.json();
   tests["Count: "  + body.items] = true; 
})()

or like this:

pm.response.json().then(body => {
   tests["Count: "  + body.items] = true;
});
like image 35
Ifaruki Avatar answered Sep 07 '25 22:09

Ifaruki