JuanSedano
JuanSedano

Reputation: 1025

Parse Json from Google Charts

I'm using json to load dynamically data into a Google Chart, the chart looks good, but i want to read the json in order to use these values to create a table with the json values.

I read the data with:

var formData = {type:"All"};
var jsonDataAll = $.ajax({
    type: "POST",
    data : formData,        
    url: "./content/chartsData.php",
    dataType:"json",
    async: false
}).responseText;

This is the response:

{
     "cols": [
        {"id":"","label":"Level","pattern":"","type":"string"},
        {"id":"","label":"Number","pattern":"","type":"number"}
      ],
      "rows": [
        {"c":[{"v":"Preschool","f":null},{"v":8,"f":null}]},
        {"c":[{"v":"Kindergarten","f":null},{"v":23,"f":null}]},
        {"c":[{"v":"Elementary","f":null},{"v":32,"f":null}]},
        {"c":[{"v":"Junior","f":null},{"v":31,"f":null}]},
      ]
}

How can get the values?

Preschool - 8
Kindergarten - 23
Elementary - 32
Junior - 31

Any ideas?

Upvotes: 1

Views: 571

Answers (3)

Mike Brant
Mike Brant

Reputation: 71384

You just need to parse the JSON to an object and then iterate through the column and row data stored in the representation to get at the data you need. That might look something like this:

var obj = JSON.parse(jsonDataAll);
// get column labels
var columns = [];
for(i=0; i<=obj.cols.length; i++) {
    columns .push(obj.cols[i].label);
}
console.log(columns); // ['Level','Number']
// get row data
var rows = [];
for(i=0; i<=obj.rows.length; i++) {
    var row = [];
    for(j=0;j<=labels.length;j++) {
        row.push(obj.rows[i].c[j].v);
    }
    rows.push(row); 
}
console.log(rows); // [['Preschool',8],['Kindergarten',23],['Elementary',32],['Junior',31]]

Upvotes: 1

NathanB
NathanB

Reputation: 311

Here is my shot at the Question. http://jsfiddle.net/7uLk3ktn/

Taking into account the JSON data you have available, here is the (jQuery) code that I have used in order to extract the data.

<h1> School data </h1>
<ul id="data">
</ul>

var json_rows = json.rows;
 $.each(json_rows, function(index, value) {
      console.log(json_rows[index].c[1].v);
      var school_name = json_rows[index].c[0].v;
      var school_value = json_rows[index].c[1].v;
      $('ul#data').append('<li>'+ school_name + ' - ' + school_value + '</li>');
 });

Upvotes: 2

Dan Hogan
Dan Hogan

Reputation: 468

Maybe something like this might get you started:

var data = '["Level","Number"]';

for(var i=0; i < obj["rows"].length; i++){
    data += ",[" + obj["rows"][i]["c"][0]["v"] +","+ obj["rows"][i]["c"][1]["v"] + "]";
}

Then the data variable can be passed into where you need in the charts part. I made this fiddle to mess around with the formatting.

I would definitely suggest checking out the Google Chart documentation.

Upvotes: 1

Related Questions