最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked May 6, 2011 at 9:09 LeemLeem 18.3k39 gold badges112 silver badges164 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

You could use the following test:

if (data instanceof Array) {
    // data is an array
} else {
    // it is not an array
}

A simple test is to check for the existence of obj.length and obj[0].

It's not 100% fool proof, but if you know that your data can only appear in one of the two formats you put in the question it should be sufficient.

发布评论

评论列表(0)

  1. 暂无评论