How to find JSON length using JSON.parse?

I have 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"}} . Therefore, ideally, I should get the length as 1, given that I have only 1 value in 0th place.

what if i have 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"}} 

I get the value as undefined if I do alert (response.length); where the answer is my JSON as above.

Any suggestions?

+4
source share
1 answer

Objects do not have the .length property ... not the way you think (this is undefined ), these are arrays that have this in order to get the length, you need to count the keys, for example:

 var length = 0; for(var k in obj) if(obj.hasOwnProperty(k)) length++; 

Or, alternatively, use the keys collection, available in most browsers:

 var length = obj.keys.length; 

MDC provides an implementation for browsers that do not yet 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 array, as these keys do not seem to be significant, for example:

 [{"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 .length as you want and still access the members by index.

+14
source

Source: https://habr.com/ru/post/1333566/


All Articles