Javascript 在 Chartjs 中显示 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44990517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:50:58  来源:igfitidea点击:

Displaying JSON data in Chartjs

javascriptjsonchart.js

提问by Jason Chen

I am trying to use Chart JSto create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:

我正在尝试使用Chart JS创建一个表,其中包含来自我的 JSON 文件的动态生成的数据点。我的代码逻辑如下所示:

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:

我的 JSON 文件同时看起来像这样:

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

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

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

Anyhow, my thinking was to use the variable datapartas 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.

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

How might I go about adding these JSON values to Chart.js?

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

回答by ?????

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>

回答by Simba

I found the solutionproposed by Bear GRiZZLY XI quite helpful. Makes use of the for.. loop.

我发现Bear GRiZZLY XI 提出的解决方案非常有帮助。使用 for.. 循环。

Let's suppose you have a json response from your api as follows:

假设您的 api 有一个 json 响应,如下所示:

var markschart = document.getElementbyId("markschart");

{
    "labels": "Maths,Geography,Physics,Chemistry,English,Biology,Music",
    "datasets": [
        {
            "label": "Student 3",
            "data": "120, 90, 45, 90, 14, 100, 88",
            "spanGaps": false
        },
        {
            "label": "Student 2",
            "data": "150, 80, 99, 100, 90, 110, 97",
            "spanGaps": false
        },
        {
            "label": "Student 1",
            "data": "140, 100, 89, 134, 120, 78, 56",
            "spanGaps": false
        }
    ]
}

in javascript you may handle the response as follows (response contains the above json packet):

在 javascript 中,您可以按如下方式处理响应(响应包含上述 json 数据包):

var mydatasets = [];
var colorslist = ["blue","orange","magenta","green","syrup","navy","bumblebee","turkish","army","ferrari"];

for(var j = 0; j < response.datasets.length; j++) {
  mydatasets.push({label: response.datasets[j].label, boderColor: colorslist[j], data: response.datasets[j].data.splits(','), spanGraphs: true});
}
var subjectsData = {
  labels: response.labels.split(','),
  datasets: mydatasets
}

var options = {
  scales: { 
   yAxes: [{
      ticks: {
             beginAtZero: true
           },
      scaleLabel: {
             display: true,
             labelString: 'Subject Perfomance',
             fontSize: 14
           }
  }]
 }
};

var studentsMarksPerformance = new Chart(markschart, {
      type: "line",
      data: subjectsData ,
      options: options
});

The above is not a complete solution but may help with implementing for..each loop in creating a line chart using Chart.js

以上不是一个完整的解决方案,但可能有助于在使用 Chart.js 创建折线图时实现 for..each 循环