Reputation: 4984
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]
}
]
}
})
Upvotes: 0
Views: 11836
Reputation: 32879
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>
Upvotes: 8