Chartjs-Chart.js using json data

7👍

Considering you have the following JSON data …

{
   "January": 65,
   "February": 59,
   "March": 80,
   "April": 81,
   "May": 56,
   "June": 55
}

You can use Object.keys() and Object.values() methods to parse labels and data respectively from that JSON data, for creating the chart.

Example

var data = {
   "January": 65,
   "February": 59,
   "March": 80,
   "April": 81,
   "May": 56,
   "June": 55
}

const CHART = document.getElementById('lineChart');

var lineChart = new Chart(CHART, {
   type: 'line',
   data: {
      labels: Object.keys(data),
      datasets: [{
         label: 'My first dataset',
         fill: false,
         lineTension: 0,
         backgroundColor: "rgba(75,192,192,0.4)",
         borderColor: "rgba(75,192,192,1)",
         borderCapStyle: 'butt',
         borderDash: [],
         borderDashOffset: 0.0,
         borderJointStyle: 'miter',
         data: Object.values(data)
      }]
   }
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.js"></script>
<div class="container">
   <div class="row">
      <div class="col-sm-6">
         <canvas id="lineChart" width="400" height="400"></canvas>
      </div>
      <div class="col-sm-6">
      </div>
   </div>
</div>

Leave a comment