1

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?

2
  • Can you add your controller code here? So it will good if we set it from code-behind. Commented Aug 8, 2015 at 22:07
  • Open your developer console (F12 in most browsers) and use console.log(theVariable); to see what it contains. Commented Aug 8, 2015 at 22:21

2 Answers 2

2

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"

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

2 Comments

what do we do by parsing the data here? i have explicitly defined in the controller that the return datatype should be json.
@user3378974 Your return type IS JSON. Just so happens that whatever method is producing the JSON is sending the jList property as a string. That's a server-side issue, not client-side. If your return type wasn't JSON, you wouldn't be able to do data.jList, it would return undefined.
0

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

1 Comment

Thanks -1. Any reason?

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.