Reputation: 132
I have a method with ajax call to the server to get json result
var jsonData = $.ajax({
url: '/Reports/GetJsonData',
type: 'GET',
dataType: 'json',
error: function (err) {
alert("Error : "+err.statusText);
}
}).responseText;
Then I can get the Following Json result to the "jsonData" variable.
[
{"LineName":"L1","Car":23,"Bus":0,"Motorcycle":0,"Person":0,"Others":0}
,{"LineName":"L2","Car":0,"Bus":0,"Motorcycle":6,"Person":0,"Others":0}
,{"LineName":"L3","Car":10,"Bus":20,"Motorcycle":36,"Person":13,"Others":0}
]
I want to convert this result to the following format
[['LineName', 'Car', 'Bus','Motorcycle', 'Person','Others'],
['L1', 23, 0, 0,0,0],
['L2', 0, 0, 6,0,0],
['L3', 10, 20, 36,13,0]]
Then I want to use it in google visualization API for drawing a graph
var data = new google.visualization.arrayToDataTable(jsonData);
I just need to know if there any simple way to convertion the data which can pass to the google.visualization
Upvotes: 2
Views: 2716
Reputation: 61275
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['table']
});
function drawChart() {
var jsonData = [
{"LineName":"L1","Car":23,"Bus":0,"Motorcycle":0,"Person":0,"Others":0},
{"LineName":"L2","Car":0,"Bus":0,"Motorcycle":6,"Person":0,"Others":0},
{"LineName":"L3","Car":10,"Bus":20,"Motorcycle":36,"Person":13,"Others":0}
];
var gglData = [];
if (jsonData.length > 0) {
// load column headings
var colHead = [];
Object.keys(jsonData[0]).forEach(function (key) {
colHead.push(key);
});
gglData.push(colHead);
// load data rows
jsonData.forEach(function (row) {
var gglRow = [];
Object.keys(row).forEach(function (key) {
gglRow.push(row[key]);
});
gglData.push(gglRow);
});
}
// arrayToDataTable is a static method, "new" keyword not needed
var data = google.visualization.arrayToDataTable(gglData);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div>
Upvotes: 3