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.
“how to count number of records in json” Code AnswerCall len(obj) to return the number of items in a JSON object obj.
To get length of json object in javascript, just use Object. keys() method with length property. it will return length of object.
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.
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):
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With