Array of Standard JSON objects to DataTable

226 views
Skip to first unread message

Michelle Stewart

unread,
Jan 7, 2013, 9:32:44 AM1/7/13
to google-visua...@googlegroups.com
I have data coming back from a server which is used for more than one purpose so I cannot change its format.  The data is formatted like so:
[{"Prod Date":"11/12/2011","Press":4,"Shift":1,"Mold":"A","Min Cycle Time":76,"Avg Cycle Time":77.042,"Max Cycle Time":78}, 
{"Prod Date":"11/12/2011","Press":5,"Shift":1,"Mold":"B","Min Cycle Time":74,"Avg Cycle Time":74.5,"Max Cycle Time":75}, 
{"Prod Date":"11/12/2011","Press":5,"Shift":1,"Mold":"C","Min Cycle Time":52,"Avg Cycle Time":85.047,"Max Cycle Time":110} 
] 
I have a function right now that converts this JSON array into a 2D array so that it can be used with arrayToDataTable().

I am about to write a new page that will have data formatted the same way for the same reasons and need to ensure it ends up in a DataTable as quickly as possible.  Because I will be writing a custom aggregation function.
I cannot guarantee what the columns will be (other than the ones I will aggregate) so it's tricky to come up with the full object for using Object Literal Notation.

Is there a simple way to take my JSON array and get it to a DataTable without having to go through my function in order to speed up processing?

Thank you,
Michelle

asgallant

unread,
Jan 7, 2013, 12:33:17 PM1/7/13
to google-visua...@googlegroups.com
Yes, there is a simple way to enter data in that format, with an arbitrary number of columns, into a DataTable:

var json = [
    {"Prod Date":"11/12/2011","Press":4,"Shift":1,"Mold":"A","Min Cycle Time":76,"Avg Cycle Time":77.042,"Max Cycle Time":78}, 
    {"Prod Date":"11/12/2011","Press":5,"Shift":1,"Mold":"B","Min Cycle Time":74,"Avg Cycle Time":74.5,"Max Cycle Time":75}, 
    {"Prod Date":"11/12/2011","Press":5,"Shift":1,"Mold":"C","Min Cycle Time":52,"Avg Cycle Time":85.047,"Max Cycle Time":110} 
];
  
// create an array of data
var dataArray = [];
var tmp = [];
for (x in json[0]) {
    tmp.push(x);
}
dataArray.push(tmp);
  
for (var i = 0; i < json.length; i++) {
    tmp = [];
    for (var j = 0; j < dataArray[0].length; j++) {
        tmp.push(json[i][dataArray[0][j]]);
    }
    dataArray.push(tmp);
}
  
var data = google.visualization.arrayToDataTable(dataArray);

Michelle Stewart

unread,
Jan 7, 2013, 1:41:58 PM1/7/13
to google-visua...@googlegroups.com
OK, that is what I am already doing.  Thank you!


On Monday, January 7, 2013 9:32:44 AM UTC-5, Michelle Stewart wrote:
Reply all
Reply to author
Forward
0 new messages