0

I have the following JS code:

var response = loadXMLDoc();
var dataset = response.data;
alert(response);
alert (dataset);

"alert(response)" prints this:

{"labels":["-inf - 10","10 - 20","20 - 30","30 - 40","40 - 50","50 - 60","60 - 70","70 - 80","80 - 90","90 - 100","100 - 110","110 - 120","120 - 130","130 - 140","140 - 150","150 - 160","160 - +inf"],"data":[3,8,7,3,7,6,6,7,5,4,10,7,4,4,7,2,0],"count":16}   

while "alert(dataset)" gives "undefined". I have tried to use

     var dataset = response["data"]; 

but it did not work as well. I want to get the data array from the JSON object. How can i do that. Thanks

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Sami
  • 7,797
  • 18
  • 45
  • 69
  • You have to parse the JSON into a JavaScript object first. See [how to parse json in javascript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript). Also note that there is no key `data` in the JSON (only `labels` and `count`). – Felix Kling May 28 '12 at 10:53
  • @Felix KlingThanks.. it worked. data key is there though. – Sami May 28 '12 at 10:57

3 Answers3

1

Use var y = JSON.parse(response); alert(y["data"])

rt2800
  • 3,045
  • 2
  • 19
  • 26
0

Seeing that you got alert to show response, it's a string, not yet an object.

You need to parse it with JSON.parse()

//load your response
var response = loadXMLDoc(),
    dataset;

//parse response
response = JSON.parse(response);

//assign data to dataset
dataset = response.data;

//Hit F12 to see the console
console.log(response);
console.log(dataset);

Here's a sample

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

Try this

var dataset = eval('(' + responce.data + ')');
Talha
  • 18,898
  • 8
  • 49
  • 66