Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the JSON data is one object or an array of objects?

I got server responsed JSON data:

var data = SERVER_RESPONSE;

this data could be an object {id: 12, name: John},

it could also be an array of objects [{id: 12, name: John}, {id: 22, name: OMG}]

In Javascript, how can I check if the JSON data is one object or an array of objects?

like image 614
Leem Avatar asked May 06 '11 09:05

Leem


People also ask

Can a JSON file be an array of objects?

JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.

What is the difference between JSON array and JSON object?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

Is JSON a string or array?

JSON is JavaScript Object Notation is used for data interchange, Array of strings is an ordered list of values with string type. So on a whole, the 'JSON array of strings' represents an ordered list of values, and It can store multiple values. This is useful to store string, Boolean, number, or an object.


1 Answers

You could use the following test:

if (data instanceof Array) {
    // data is an array
} else {
    // it is not an array
}
like image 59
Darin Dimitrov Avatar answered Sep 19 '22 18:09

Darin Dimitrov