Skip to content Skip to sidebar Skip to footer

Use Json File With Chart.js

I've been looking all over chart.js-related questions, but not two developers seem to be giving the same answer on how to display a chart using chart.js + JSON. I am trying to disp

Solution 1:

Couple of Issues :

  • since $.getJSON() method is asynchronous, you should construct the chart inside it­'s callback function.
  • you are looping through the response data incorrectly. could be as simple as :

­

var labels = data.customers[0].amounts.map(function(e) {
       return e[0];
    });

    vardata = data.customers[0].amounts.map(function(e) {
       return e[1];
    });
  • you are adding labels array to your dataset, while it belogns to the data object.

Here is the revised version of your code :

$.getJSON("https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c", function(data) {
   var labels = data.customers[0].amounts.map(function(e) {
      return e[0];
   });
   var data = data.customers[0].amounts.map(function(e) {
      return e[1];
   });

   var ctx = document.getElementById('myChart').getContext('2d');
   var chart = newChart(ctx, {
      type: 'line',
      data: {
         labels: labels,
         datasets: [{
            backgroundColor: 'rgb(129, 198, 2228)',
            borderColor: 'rgb(0, 150, 215)',
            data: data
         }]
      },
      options: {
         responsive: 'true',
      }
   });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script><canvasid="myChart"></canvas>

Post a Comment for "Use Json File With Chart.js"