javascript 如何使用 JSON.parse 查找 JSON 的长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4546159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find length of JSON using JSON.parse?
提问by Amol
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
{"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。
what if i have a JSON like this
如果我有这样的 JSON 怎么办
{"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"}}
I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above
如果我执行 alert(response.length); 我得到的值为 undefined; 如上所述,响应是我的 JSON
Any suggestions?
有什么建议?
回答by Nick Craver
Objects don't have a .lengthproperty...not in the way you're thinking (it's undefined), it's Arraysthat have that, to get a length, you need to count the keys, for example:
对象没有.length属性......不是你想的那样(它是undefined),它是具有属性的数组,要获得长度,您需要计算键,例如:
var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;
Or, alternatively, use the keyscollectionavailable on most browsers:
或者,使用大多数浏览器上可用的keys集合:
var length = obj.keys.length;
MDC provides an implementation for browsers that don'talready have .keys:
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:
或者,选项 #3,实际上使您的 JSON 成为一个数组,因为这些键似乎没有多大意义,如下所示:
[{"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"}]
Then you can use .lengthlike you want, and still access the members by index.
然后您可以随意使用.length,并且仍然可以通过索引访问成员。

