Horje
How to Count Records in JSON array using JavaScript and Postman ?

In this article, we are going to explore how JavaScript and Postman are used to count the number of records returned in a JSON array.

  • Send a Request: Send a request to fetch the JSON array from your API endpoint in Postman.
  • Access JSON Response: In the Postman test scripts tab, you can access the JSON response body using the pm.response.json() method.
  • Count Records: Use JavaScript array methods to count the records in the JSON array. For example, you can use the length property of the array.

Here I have an API endpoint of my own that returns all the users registered in my application. We are going to use this API to count the number of records returned in the JSON response.

Screenshot-2024-03-15-162219

API Endpoint

Steps to Count records in JSON array using JavaScript and Postman:

  • Set Up Postman – Install and set up postman from their official website.
  • Create Request – Open Postman and create a new request. This request can be for any API endpoint that returns a JSON response containing an array of records.
  • Write Test Script – Go to the test tab under the endpoint input. Here type the following script to count the records
  • Run the request – Send the request to the API endpoint by clicking the “Send” button.
  • View Test Results – After running the request, switch to the “Test Results” tab in Postman. You should see the output of the test script, which will display the count of records in the JSON array.
var data = pm.response.json();

pm.test('Number of users returned = ' + data.length);
Screenshot-2024-03-15-162810

Check the test results

Testing the Count:

If we want to check something related to the count, like checking whether it is equal to 2 or not, we can also do that with the help of a script.

var data = pm.response.json();

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

Output:

Screenshot-2024-03-15-165003

Testing for only 2 records




Reffered: https://www.geeksforgeeks.org


Node.js

Related
Important npm Commands Important npm Commands
Conditionals in Pug View Engine Conditionals in Pug View Engine
How to use Attributes in Pug ? How to use Attributes in Pug ?
How to send Basic Auth with Axios in React & Node ? How to send Basic Auth with Axios in React & Node ?
Getting Started with Postman API Testing Getting Started with Postman API Testing

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16