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

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

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?

回答1:

You could use the following test:

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


回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!