0

I have a jsfiddle here - https://jsfiddle.net/nhww0uor/4/

I have a simple line graph using chart.js

The data is hard coded in the code.

How do I do the same thing but with data from json

    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: ['January','February','March','April','May','June'],
            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: [65,59,80,81,56,55]
                }
            ]
        }
    })
0

1 Answer 1

8

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. How would this work with an external JSON source like for example rki.marlon-lueckert.de/api/states

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.