Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find length of JSON using JSON.parse?

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.

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"}}

I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above

Any suggestions?

like image 995
Amol Avatar asked Dec 28 '10 12:12

Amol


People also ask

What is JSON parse () method?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is JSON object size?

The size of a JSON array is the number of elements. As JSON arrays are zero terminated, the size of a JSON array is always the last index + 1.

How long does it take to parse JSON?

So you should expect to spend 2 or 3 seconds parsing one gigabyte of JSON data.


1 Answers

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++;

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

var length = obj.keys.length;

MDN provides an implementation for browsers that don't already 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:

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

like image 177
Nick Craver Avatar answered Sep 22 '22 04:09

Nick Craver