简体   繁体   中英

Dynamically Creating Json Array Javascript

I am using Chart.js and in order to generate charts, the data loaded in seems to be in Json format. For example

var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
    {
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 55, 40]
    },
    {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: [28, 48, 40, 19, 86, 27, 90]
    }
]};

I am trying to create a variable similar to the example above by using data from a Json response... The Json response is formated as:

{
"points": {
"0": {
  "data_in": 8606441,
  "data_out": 25531384,
  "num_request": 2712,
  "time": "Fri, 10 Jul 2015 00:00:00 GMT"
},
 "1": {
  "data_in": 1719403,
  "data_out": 3463972,
  "num_request": 1446,
  "time": "Fri, 10 Jul 2015 01:00:00 GMT"
 },
 "2": {
  "data_in": 284120,
  "data_out": 3244090,
  "num_request": 786,
   "time": "Fri, 10 Jul 2015 02:00:00 GMT"
 },

I am trying to populate a variable called temp to match the Chart.js format.

   var temp = {
   labels: [],
   dataset: [
    {
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: []
  }
  ]
 };



    $.getJSON('/api/time_points', data, function(data){
    $.each(data.points, function( index, value ){
        temp.labels.push(data.points[index].time);
        temp.dataset[data].push(data.points[index].num_request);
    });

});

This does not seem to be working however. Any ideas?

temp.dataset is an array, and you are trying to use data, an object, as an index.

It should be something like:

temp.dataset[0].push(data.points[index].num_request);

(or whatever the index should be) not:

temp.dataset[data].push(data.points[index].num_request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM