0

I have json response showing 4 values (image showing 3) for this object companies[0].salesReps How to verify postman test for total no of Sales employee and print their names on console.

x.companies[0].salesReps[0].name
x.companies[0].salesReps[1].name
x.companies[0].salesReps[2].name

list

Tried this saying undefined

emp = JSON.parse(responseBody(companies[0].salesReps));
    var listcnt = emp.length;
    console.log(listcnt)

Any thing missing :) Thanks

GPs
  • 67
  • 1
  • 10

2 Answers2

2

Not sure about the structure of your response body, but this should do it. Happy to adapt it, once you've posted your complete response body.

const resBody = pm.response.json();

const numberOfSalesEmployees = resBody.companies[0].salesReps.length;

console.log("Number of sales employees:" + numberOfSalesEmployees);

for (var i = 0; i < numberOfSalesEmployees; i++){
    console.log("Name of sales rep " + i + ": " + resBody.companies[0].salesReps[i].name);
}

pm.test("Number of sales employees is 4", function () {
    pm.expect(numberOfSalesEmployees).to.eql(4);
});
Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
  • Thanks Chris, getting output for all four sales employee name as ` Name of sales rep 0: [object Object]` – GPs Oct 13 '20 at 15:50
  • 1
    As requested, please share your complete response body. Only then I can be sure about how to address the data and make the code work. – Christian Baumann Oct 13 '20 at 15:52
  • Got it work thanks Chris it was pointing to wrong object. Updated this line and all working now :) `console.log("Name of sales rep " + i + ": " + (resBody.companies[0]).salesReps[i].name);` – GPs Oct 13 '20 at 16:18
  • 1
    Cool. Updated my answer. Thanks for accepting it in case it does what you asked for. – Christian Baumann Oct 13 '20 at 16:22
  • Accepted your answer :) – GPs Oct 13 '20 at 16:48
-1

I think you'd be better off parsing responseBody first (before trying to access data in the response), so:

var parsedResponseBody = JSON.parse(responseBody);
var listCnt = parsedResponseBody.companies[0].salesReps.length;