Displaying JSON data in Chartjs(在 Chartjs 中显示 JSON 数据)
问题描述
I am trying to use Chart JS to create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:
var datapart;
for (i = 0; i < jsonfile.jsonarray.length; i++){
datapart += {
label: jsonfile.jsonarray[i].name,
data: [jsonfile.jsonarray[i].age]
};
}
var config = {
type: 'line',
data: {
labels: ["Graph Line"],
datasets: [datapart]
}
}
My JSON file meanwhile looks something like so:
{
"jsonarray": [
{
"name": "Joe",
"age": 12
},
{
"name": "Tom",
"age": 14
}
]
}
The config
variable houses the configuration settings for ChartJS, including setting datapoints. When loaded into ChartJS, config
provides information needed to display my chart.
Anyhow, my thinking was to use the variable datapart
as a means of appending the datasets using my for loop. Unfortunately the code produces no results. I understand that my method for appending variables is faulty, but am unsure how to proceed.
How might I go about adding these JSON values to Chart.js?
Your approach on constructing the chart is completely inappropriate. Here is the proper way, that you should follow :
var jsonfile = {
"jsonarray": [{
"name": "Joe",
"age": 12
}, {
"name": "Tom",
"age": 14
}]
};
var labels = jsonfile.jsonarray.map(function(e) {
return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.age;
});;
var ctx = canvas.getContext('2d');
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Graph Line',
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
}]
}
};
var chart = new Chart(ctx, config);
<script src="aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvQ2hhcnQuanMvMi42LjAvQ2hhcnQubWluLmpz"></script>
<canvas id="canvas"></canvas>
这篇关于在 Chartjs 中显示 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Chartjs 中显示 JSON 数据
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01