Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting records in JSON array using javascript and Postman

I have a control that returns 2 records:

{   "value": [     {       "ID": 5,       "Pupil": 1900031265,       "Offer": false,     },     {       "ID": 8,       "Pupil": 1900035302,       "Offer": false,       "OfferDetail": ""     }   ] } 

I need to test via Postman, that I have 2 records returned. I've tried various methods I've found here and elsewhere but with no luck. Using the code below fails to return the expected answer.

responseJson = JSON.parse(responseBody); var list = responseBody.length; tests["Expected number"] = list === undefined || list.length === 2; 

At this point I'm not sure if it's the API I'm testing that's at fault or my coding - I've tried looping through the items returned but that's not working for me either. Could someone advise please - I'm new to javascript so am expecting there to be an obvious cause to my problem but I'm failing to see it. Many thanks.

like image 673
Chrissi Avatar asked Mar 14 '16 12:03

Chrissi


People also ask

How do I count the number of records in JSON?

“how to count number of records in json” Code AnswerCall len(obj) to return the number of items in a JSON object obj.

How do you count objects in JSON?

To get length of json object in javascript, just use Object. keys() method with length property. it will return length of object.

Does postman parse JSON?

Postman does its own serialization of the data, since we cannot know what you intend to do with your data. By using JSON. stringify() and JSON. parse() yourself, you help Postman to store and interpret the data more easily, removing unexpected results in your application.


2 Answers

In postman, under Tests section, do the following (screenshot below): var body = JSON.parse(responseBody); tests["Count: " + body.value.length] = true;

Here is what you should see (note: I replaced responseBody with JSON to mock up example above): enter image description here

like image 155
RC_02 Avatar answered Sep 18 '22 12:09

RC_02


Correct your json. and try this.

=======================v

var test = JSON.parse('{"value": [{"ID": 5,"Pupil": 1900031265,"Offer": false},{"ID": 8,"Pupil": 1900035302,"Offer": false,"OfferDetail": ""}] }')      test.value.length; // 2 

So you need to identify the array in the json (starting with the [ bracket. and then take the key and then check the length of the key.

like image 40
Kaushik Avatar answered Sep 19 '22 12:09

Kaushik