如何使用JSON.parse查找JSON的长度? [英] How to find length of JSON using JSON.parse?
问题描述
我有一个像这样的杰森
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"}}
.
因此,理想情况下,考虑到我在第0个位置上只有1个值,我应该将长度设为1.
I have a Json like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"}}
.
So ideally i should get length as 1 considering i have only 1 value on 0th location.
如果我有这样的JSON
what if i have a JSON like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}
如果我发出警报(response.length),我将获得未定义的值;如上所述,响应是我的JSON
I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above
有什么建议吗?
推荐答案
对象没有.length
属性...不是您正在考虑的方式(它是undefined
),而是 Arrays 要获得长度,您需要对键进行计数,例如:
Objects don't have a .length
property...not in the way you're thinking (it's undefined
), it's Arrays that have that, to get a length, you need to count the keys, for example:
var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;
或者,或者使用 keys
集合在大多数浏览器上可用:
Or, alternatively, use the keys
collection available on most browsers:
var length = obj.keys.length;
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
或者,选择#3,实际上使JSON成为数组,因为这些键似乎意义不大,如下所示:
Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:
[{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}]
然后,您可以根据需要使用.length
,并且仍然可以通过索引访问成员.
Then you can use .length
like you want, and still access the members by index.
这篇关于如何使用JSON.parse查找JSON的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!