Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a JSON response element is an array?

I am receiving the next JSON response

    {     "timetables":[         {"id":87,"content":"B","language":"English","code":"en"},                                                         {"id":87,"content":"a","language":"Castellano","code":"es"}],     "id":6,     "address":"C/Maestro José"     } 

I would like to achieve the next pseudo code functionality

for(var i in json) {                 if(json[i]  is Array) {     // Iterate the array and do stuff     } else {     // Do another thing     } } 

Any idea?

like image 350
Sergio del Amo Avatar asked Jun 04 '09 16:06

Sergio del Amo


People also ask

How do you know if a response is an array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

Can JSON response be an array?

JSON can be either an array or an object.

How do we identify JSON array and JSON object?

You can check the character at the first position of the String (after trimming away whitespace, as it is allowed in valid JSON). If it is a { , you are dealing with a JSONObject , if it is a [ , you are dealing with a JSONArray .

How do you check if a variable is an array in JavaScript?

The Array. isArray() method checks whether the passed variable is an Array object. It returns a true boolean value if the variable is an array and false if it is not.


1 Answers

There are other methods but, to my knowledge, this is the most reliable:

function isArray(what) {     return Object.prototype.toString.call(what) === '[object Array]'; } 

So, to apply it to your code:

for(var i in json) {                         if(isArray(json[i])) {     // Iterate the array and do stuff     } else {     // Do another thing     } } 
like image 140
James Avatar answered Oct 02 '22 17:10

James