Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - Displaying JSON data in Chartjs

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...