Counting entries in a 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 check through Postman that I have 2 entries. I tried various methods that I found here and elsewhere, but no luck. Using the code below does not return the expected response.

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

At this point, I'm not sure if this is an API that I am testing for fault or my coding. I tried iterating over the returned elements, but this also does not work for me. Could someone advise, please, I am new to javascript, so I expect this to be the obvious reason for my problem, but I don't see it. Many thanks.

+7
source share
9

json. .

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

test.value.length; // 2
+7

- , , try

var list = responseJson.value.length;
+5

Tests ( ): var body = JSON.parse(responseBody); tests["Count: " + body.value.length] = true;

(: responseBody JSON, ): enter image description here

+4

,

//parsing the Response body to a variable
    responseJson = JSON.parse(responseBody);

//Finding the length of the Response Array
    var list = responseJson.length;
    console.log(list);
    tests["Validate service retuns 70 records"] = list === 70;

enter image description here

+3

, :

responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;

, , .

console.log(responseJson.length);
+1

, JSON. , -

responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = responseJson.value.length === list;
0

First of all, you must convert the response to json and find the path to the value. Value is an array. You must call the length function to find out how many objects there are and check the expected size.

pm.test("Validate value count", function () {
    pm.expect(pm.response.json().value.length).to.eq(2);
});
0
source

As mentioned in the comments, you should check responseJson.value.length

responseJson = JSON.parse(responseBody); tests["Expected number"] = typeof responseJson === 'undefined' || responseJson.value.length;

-1
source

Working code

 pm.test("Verify the number of records",function()
 {
   var response = JSON.parse(responseBody); 
   pm.expect(Object.keys(response.value).length).to.eql(5);

 });
//Please change the value in to.eql function as per your requirement    
//'value' is the JSON notation name for this example and can change as per your JSON
-1
source

All Articles