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);
Njax3SmmM2x2a0Zf7Hpd
  • 1,354
  • 4
  • 22
  • 44

3 Answers3

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
Diode
  • 24,570
  • 8
  • 40
  • 51
  • 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 https://stackoverflow.com/questions/20881213/converting-javascript-object-with-numeric-keys-into-array – Ralph Yozzo Aug 06 '18 at 00:58
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);
Scott
  • 21,211
  • 8
  • 65
  • 72
  • 4
    Note that the JSON has to be correctly [formatted](https://developers.google.com/chart/interactive/docs/reference#dataparam) with `cols` and `rows` arrays – SymbolixAU May 08 '17 at 02:36
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));
        }
    });
}
Skandix
  • 1,916
  • 6
  • 27
  • 36