JSON => GoogleCharts formatting

2019-09-08 06:12发布

问题:

I am desperately trying to get my GoogleChart working. This code always throws an error though:

        function drawChart() 
        { 
          var data = new google.visualization.DataTable(); 
          data.addColumn('number', 'hour'); 
          data.addColumn('number', 'TriggerCount'); 
          var JsonManuallyEncoded = '{1:{1:01,2:4},2:{1:03,2:4},3:{1:04,2:48},4:{1:05,2:59},5:{1:06,2:59},6:{1:07,2:87},7:{1:08,2:62},8:{1:09,2:46},9:{1:10,2:61},10:{1:11,2:71},11:{1:12,2:54},12:{1:13,2:61},13:{1:14,2:89},14:{1:15,2:58},15:{1:16,2:122},16:{1:17,2:108},17:{1:18,2:64},18:{1:19,2:50},19:{1:20,2:10},20:{1:21,2:18}};'
          data.addRows(JsonManuallyEncoded);


        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); 
        chart.draw(data);}

The Firefox console says: "Argument given to addRows must be eiter a number or an array". I suspect that the format of the JSON string is not correct, but I cannot figure out what's wrong. Can somebody please identify my mistake? It's probably trivial but I am spending hours on this already...

回答1:

Have you looked at the documentation for addRows? but you should not pass the row data to addRows as a JSON encoded string, you should pass a array of arrays data structure. I think there may be other API functions for passing a JSON string so i recommend you to read the documentation and look at the examples.