Write response from JSON Array to Google Chart and

2019-08-11 04:48发布

问题:

I have a google chart code like below

 <script type="text/javascript">
 // Load the Visualization API and the piechart package.
 google.load('visualization', '1.0', {'packages':['corechart']});

 // Set a callback to run when the Google Visualization API is loaded.
 google.setOnLoadCallback(drawChart);

 // Callback that creates and populates a data table,
 // instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
 // Create the data table.
     var data = new google.visualization.DataTable();
     data.addColumn('string', 'Type');    
     data.addColumn('number', 'Total');
     data.addRows([
      ['Damage', 3],
      ['Lost', 1]
    ]);
 // Instantiate and draw our chart, passing in some options.
  var chart = new 
  google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, options);
  }
  </script> 

I want to insert with json api array like below

    "status": 200,
    "message": "OK",
    "data": [
     {
       "_id": {
       "report_type": "robbery"
        },
        "report_type": "robbery",
        "Counts": 11
      },
      {
         "_id": {
         "report_type": "property_damage"
          },
         "report_type": "property_damage",
          "Counts": 39
     },
     {
        "_id": {
        "report_type": null
         },
        "report_type": null,
        "Counts": 2
     }
    ]

I want to change type and total in the google chart above with report_type and Counts value in api.

I have tried write code below, but the results is not coming

   function drawChart() {
     $.ajax({
     url: "api-url",
     type: "GET",
     success: function (data) {
       var arrReport = [['Type', 'Total']];

      $.each(data, function (index, value) {
      arrReport.push([value.data.report_type, value.data.Counts]);
     });

     var options = {
    'width':400,
    'height':300
     };

     var figures = google.visualization.arrayToDataTable(arrReport)

     var chart = new 
     google.visualization.PieChart(document.getElementById('chart_div'));

     chart.draw(figures, google.visualization.PieChart(options));
    }
   });
  }

Do you know where's the error from my code ?

Thank you

回答1:

if the following is the json you are receiving...

"status": 200,
"message": "OK",
"data": [
 {
   "_id": {
   "report_type": "robbery"
    },
    "report_type": "robbery",
    "Counts": 11
  },
  {
     "_id": {
     "report_type": "property_damage"
      },
     "report_type": "property_damage",
      "Counts": 39
 },
 {
    "_id": {
    "report_type": null
     },
    "report_type": null,
    "Counts": 2
 }
]

in the following data argument,
then you should be looping on --> data.data
and accessing the values as --> value.report_type & value.Counts

  var arrReport = [['Type', 'Total']];

  $.each(data.data, function (index, value) {
    arrReport.push([value.report_type, value.Counts]);
  });

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  var options = {
    width: 400,
    height: 300
  };
  var arrReport = [['Type', 'Total']];
  var figures;

  // will fail here on SO
  $.ajax({
    url: 'api-url',
    type: 'GET'
  }).done(function (data) {

    drawChart(data);

  }).fail(function () {
    // draw with hard-coded data, for example purposes
    var data = {
      "status": 200,
      "message": "OK",
      "data": [
       {
         "_id": {
         "report_type": "robbery"
          },
          "report_type": "robbery",
          "Counts": 11
        },
        {
           "_id": {
           "report_type": "property_damage"
            },
           "report_type": "property_damage",
            "Counts": 39
       },
       {
          "_id": {
          "report_type": null
           },
          "report_type": null,
          "Counts": 2
       }
      ]
    };

    drawChart(data);

  });

  function drawChart(data) {
    $.each(data.data, function (index, value) {
      arrReport.push([value.report_type, value.Counts]);
    });
    figures = google.visualization.arrayToDataTable(arrReport);
    chart.draw(figures, options);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


NOTES:

1) you should be using the newer library loader.js

<script src="https://www.gstatic.com/charts/loader.js"></script>

instead of jsapi, according to the release notes...

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

this will only change the load statement, see above snippet.

2) google.visualization.PieChart -- should be removed here --> chart.draw(figures, options);



回答2:

I think you are missing with API Url Like,

$.ajax({
       url: "api-url",
       type: "GET",
       success: function (data) {
});

Assumed the API Url in a variable so it should be-

$.ajax({
           url: api-url,
           type: "GET",
           success: function (data) {
    });