Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if Postman response body Json is an array or object

I have a API that I'm testing and I'm expecting responseBody to be a Json object (starts with "{"). However it could be that due to an unexpected event the response could be returned as an array (starts with "[").

How can I determine the type (array or object) of responseBody using Postman tests?

So far the best I have is: When expecting an object (not an array)

var bodyJson = pm.response.json();
tests["Response should not be an array"] = !(bodyJson instanceof Array);
like image 317
ajgreyling Avatar asked Dec 18 '18 10:12

ajgreyling


People also ask

How check if object is JSON array?

Check if Variable is Array ? Sometimes, you need to check a parsed JSON object or a variable to see if it's an array before iteration or before any other manipulation. You can use the Array. isArray method to check if a variable is an array.

Is JSON object or array?

JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.

How do you check body response in Postman?

The Postman Body tab gives you several tools to help you understand the response quickly. You can view the body in one of four views: Pretty, Raw, Preview, and Visualize. in the results pane. You can also place your cursor in the response and select ⌘+F or Ctrl+F.


1 Answers

You could just use:

pm.test('is an Array', () => pm.expect(pm.response.json()).to.be.an('array').but.not.an('object'))

Taken from ChaiJS - which is built-in to the native Postman application.

like image 58
Danny Dainton Avatar answered Nov 18 '22 06:11

Danny Dainton