How can I convert json string to google.visualization.DataTable?
Asked Answered
P

3

9

I am getting a json string from the response. How can I create a data table from that?

e.g.

var jasonString = "..........";

var data = new google.visualization.DataTable(jasonString);
Parallelepiped answered 3/6, 2013 at 11:59 Comment(1)
is the JSON really ".........." ?Supernormal
M
15

You can use the function arrayToDataTable

var jsonString = ".........."; // json string of array
var array  = JSON.parse(jsonString);

var dataTableData = google.visualization.arrayToDataTable(array);

// use dataTableData to build dataTable
Molecule answered 3/6, 2013 at 12:52 Comment(1)
This is only for a very special case of JSON string. If you have a random JSON object and you'd like to show it in a DataTable, then convert to an array first. See #20881713Kanazawa
F
4

According to this page it says you can just put the JSON response directly into google.visualization.DataTable

var data = new google.visualization.DataTable(jsonData);
Flung answered 3/3, 2014 at 19:2 Comment(1)
Note that the JSON has to be correctly formatted with cols and rows arraysActinouranium
C
1

You can do:

google.charts.load('current', { 'packages': ['line'] });
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var json = $.ajax({
        url: "GetFaturamentoMes",
        dataType: "json",
        success: function (jsonData) {
            var data = new google.visualization.DataTable();
            data.addColumn('number', 'Mês');
            data.addColumn('number', 'Faturamento Por Mês');

            for (var i = 0; i < jsonData.length; i++) {
                mes = jsonData[i].Mes;
                total = jsonData[i].Total;
                data.addRow([mes, total]);
            }
            var options = {
                chart: {
                    title: 'Gráfico de Faturamento Mensal',
                    subtitle: 'Moeda (R$)'
                },
                width: 600,
                height: 300,
                axes: {
                    x: {
                        10: { side: 'top' }
                    }
                }
            };
            var chart = new google.charts.Line(document.getElementById('line_top_x'));
            chart.draw(data, google.charts.Line.convertOptions(options));
        }
    });
}
Congo answered 28/2, 2018 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.