Revolucion for Monica
Revolucion for Monica

Reputation: 3296

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.

Upvotes: 4

Views: 13886

Answers (4)

Danny Dainton
Danny Dainton

Reputation: 25881

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.

Upvotes: 10

Ilijanovic
Ilijanovic

Reputation: 14904

.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;
});

Upvotes: 2

Puneet Singh
Puneet Singh

Reputation: 3543

You need to define the test in the postman, and then inside that you can check the no of object in the response as shown in below code.

pm.test("Item count should be 5", function () {
  var jsonData = pm.response.json();
  pm.expect(jsonData.items.length).to.eql(5);
});

I have used a static count, but in your test scripts you can also use dynamic variables

Upvotes: 1

Anurag Arya
Anurag Arya

Reputation: 32

var body = JSON.parse(responseBody);
tests["Count: "  + Object.keys(body.items).length] = true;

I suppose postman return json and might not always need to parse it, You then count the length of your "items" using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Upvotes: -1

Related Questions