Reputation: 159
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-
data.jList.length
-- < giving 200 like something as outputObject.keys(data).length
-- < giving 200 like something as outputObject.keys(data['jList']).length
-- < giving 1 as outputHow do I get 2 as length output of the above array?
Upvotes: 1
Views: 9691
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
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