8

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?

1
  • Please show the code you are using to fetch the JSON Commented Dec 28, 2010 at 12:51

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

Comments

1
let _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"}}';
let your_json = $.parseJSON(_json);
const size = Object.keys(your_json).length;

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.