I have a google chart which currently has some hardcoded values that look like this:
var data = google.visualization.arrayToDataTable([
['Omzet', 'Omzet deze dag'],
['Ma', 1000],
['Di', 1170],
['Wo', 660],
['Do', 1030],
['Vr', 1030],
['Za', 1030],
['Zo', 1030]
]);
Now this is my json object that I want to use:
{"do":"11495","vr":"8985","za":0,"zo":"18990","ma":"27490","di":0,"wo":0}
How can I convert above object so that I can use it with google charts?
I tried following this tutorial here . But my chart is empty when I use that code.
How can I use my json object for this chart?
first, create the data table, for a line chart, the second column must be a number.
var jsonData = {"do":"11495","vr":"8985","za":0,"zo":"18990","ma":"27490","di":0,"wo":0};
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
then loop on the keys of your json,
use the key as the x value,
and the valud of the key as y
since the value is stored as a string,
we will need to convert to a number,
using parseFloat
or parseInt
for (var key in jsonData) {
data.addRow([key, parseFloat(jsonData[key])]);
}
see following working snippet...
google.charts.load('current', { packages: ['corechart'] }).then(function () { var jsonData = {"do":"11495","vr":"8985","za":0,"zo":"18990","ma":"27490","di":0,"wo":0}; var data = new google.visualization.DataTable(); data.addColumn('string', 'x'); data.addColumn('number', 'y'); for (var key in jsonData) { data.addRow([key, parseFloat(jsonData[key])]); } var chart = new google.visualization.LineChart(document.getElementById('chart')); chart.draw(data); });
<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.