Question

I am stuck (again!) and cannot seem to find an example for this. I have tried multiple variations of extracting and formatting the data to no avail.

I have the following data which comes in JSON format via server script:

[{ 
   "franchisee_name":"John Smith",
   "dish_menu":"Breakfast",
   "dish_title":"Bagels",
   "hq_price":"9.00",
   "store_price":"18.00",
   "valid_from_date":"2014-04-13",
   "valid_to_date":"9999-12-31"
 },
 {
   "franchisee_name":"Sam Jones",
   "dish_menu":"Breakfast",
   "dish_title":"Muesli",
   "hq_price":"8.00",
   "store_price":"13.00",
   "valid_from_date":"2014-04-13",
   "valid_to_date":"9999-12-31"
  },  ......

I want to place it into a Google Visualization table using

var data = google.visualization.arrayToDataTable(jsonData);

I understand the data needs to look like below:

['Franchisee', 'Menu Type','Dish', 'HQ Price', 'Store Price', 'Valid From', 'Valid To'], <-- header row         
['John Smith',  'Breakfast', 'Bagels', '9.00', '18.00', '2014-04-13', '9999-12-31'], <-- data row
....

My code for doing this is:

jQuery.getJSON( url, function( data ) {

   var header = ['Franchisee', 'Menu Type','Dish', 'HQ Price', 'Store Price', 'Valid From', 'Valid To'];            
   var row = "";            
   var rows = new Array();

   jQuery.each( data, function( i, d ) {
    row = [ d.franchisee_name, d.dish_menu, d.dish_title, int(d.hq_price), int(d.store_price), d.valid_from_date.toString(), d.valid_to_date.toString() ];
    rows.append(row);
   });  

   var jsonData = [header].concat(rows);
   var data = google.visualization.arrayToDataTable(jsonData);

   // Set chart options
   var options = {
    showRowNumber: 'false'
   };

   // Instantiate and draw our chart, passing in some options.
   var chart = new google.visualization.Table(document.getElementById('hq_report_div'));
   chart.draw(data, options);   
});

But I get the error Invalid row type for row 0 and have not found an example of how to tackle this. Thanks for any help!

Was it helpful?

Solution

By declaring var data in your callback function, you fall prey to the hoisting mechanism of javascript and its accompanying scopes subtleties1. Basically, your declaration goes to the top of the function and masks your named argument : data isn't equal to [...] but to undefined, see this Fiddle http://jsfiddle.net/dVaC2/ to illustrate my point.

Rename your variable to gdata for example (and use parseInt() instead of int() and [].push instead of [].append) :

var gdata = google.visualization.arrayToDataTable(jsonData);
// ...
chart.draw(gdata, options);  

And a demo http://jsfiddle.net/dVaC2/1/


1 See http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html or Javascript function scoping and hoisting for example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top