[Chartjs]-Use JSON file with chart.js

4👍

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];
    });

    var data = 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 = new Chart(ctx, {
      type: 'line',
      data: {
         labels: labels,
         datasets: [{
            backgroundColor: 'rgb(129, 198, 2228)',
            borderColor: 'rgb(0, 150, 215)',
            data: data
         }]
      },
      options: {
         responsive: 'true',
      }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment