在Chartjs中显示JSON数据 [英] Displaying JSON data in Chartjs

查看:194
本文介绍了在Chartjs中显示JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用图表JS 创建一个表,该表具有来自我的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]
   }
}

与此同时,我的JSON文件如下所示:

My JSON file meanwhile looks something like so:

{
"jsonarray": [
    {
      "name": "Joe",
      "age": 12
    },
    {
      "name": "Tom",
      "age": 14
    }
]
}

config变量包含ChartJS的配置设置,包括设置数据点.加载到ChartJS中后,config提供显示我的图表所需的信息.

The config variable houses the configuration settings for ChartJS, including setting datapoints. When loaded into ChartJS, config provides information needed to display my chart.

无论如何,我的想法是使用变量datapart作为使用我的for循环追加数据集的一种方式.不幸的是,该代码没有任何结果.我知道我添加变量的方法有问题,但是不确定如何进行.

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.

如何将这些JSON值添加到Chart.js?

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="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

这篇关于在Chartjs中显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆