user3378974
user3378974

Reputation: 159

Cannot get the length of JSON array in javascript

I have read other issues regarding accessing a json array in javascript, but nothing helped in my case. I am receiving the below json in jquery ajax call.

{"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date
\":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description
\":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980
}]"}

receiving method-

$.getJSON("url",
                {var : Val},
                function(data){
                    here...

All I want is to count the JSON objects in this array. In the above case I want an length output as 2 but I'm not getting it. I have tried below things-

  1. data.jList.length -- < giving 200 like something as output
  2. Object.keys(data).length -- < giving 200 like something as output
  3. Object.keys(data['jList']).length -- < giving 1 as output

How do I get 2 as length output of the above array?

Upvotes: 1

Views: 9691

Answers (2)

Jan
Jan

Reputation: 5815

The jList property of the object is just a string, so you need to convert it to a Javascript object using JSON.parse().

// Dummy of your "data" variable
var data = {"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date \":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description \":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980 }]"};

var myList = JSON.parse(data.jList);
alert(myList.length); // Alerts "2"

Upvotes: 2

Amit
Amit

Reputation: 46323

"jList":"[{\"added_by\":\"... is not an array, it's a string (and that's why it's length is 456 or 200 if you change the question).

Remove the surrounding double-quotation marks for it to be an array. Then you'll have Array.prototype.length.

Upvotes: 0

Related Questions