如何将Json转换为Google可视化数据表 [英] How To Convert Json to google visualization datatable
问题描述
我有一个Ajax调用方法来获得json结果。 b $ b url:'/ Reports / GetJsonData',
类型:'GET',
dataType:'json',
错误:function(err){
alert(错误:+ err.statusText);
}
})。responseText;
然后我可以将以下Json结果添加到jsonData变量中。
$ b
[
{LineName:L1,Car:23,Bus:0,Motorcycle Person:0,Others:0}
,{LineName:L2,Car:0,Bus:0,摩托车:6, 其他:0}
,{LineName:L3,Car:10,Bus:20,Motorcycle:36,Person:13,Others:0}
]
我想将此结果转换为以下格式
[['LineName','Car','Bus','Motorcycle','Person','Others'],
[ 'L1',23,0,0,0,0],
['L2',0,0,6,0,0],
['L3',10,20,36, 13,0]]
然后我想在Google可视化API中使用它来绘制图表 p>
var data = new google.visualization.arrayToDataTable(jsonData);
我只需要知道是否有任何简单的方法来转换可传递给Google的数据。可视化
请参阅以下工作片段... $ b
< script src =https://www.gstatic.com/charts/loader.js>< / script>< div id =table_div>< / div>
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
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>
这篇关于如何将Json转换为Google可视化数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!