Search code examples
javascriptjsonchartscanvasjs

Dynamic Chart with JSON data - CanvasJS


I have an issue generating a chart with CanvasJS.

Basically I get the data from the API, I can see and check the JSON array but when I'm going to generate the dataPoint for the graph I get 2 errors: data invalid on the data field and NaN on the value field.

Can someone give me a hint?

// Fetching the data
fetch('https://example.com/my/endpoint').then(response => {
  return response.json();
}).then(data => {
  // Work with JSON data here
 var jsonData = data;
 // Generating Data Points
 var dataPoints = [];
 
for (var i = 0; i <= jsonData.length - 1; i++) {
    dataPoints.push({ y: new Date(jsonData[i].source_ts), x: Number(jsonData[i].xyzw) });
    console.log(dataPoints);
}

var chart = new CanvasJS.Chart("chartContainer", {
    data: [
        {
            dataPoints: dataPoints,
            type: "line",
        }
    ]
});

chart.render();
}).catch(err => {
 throw new Error( 'Impossible to get data' );
});

Cheers


Solution

  • You were not intreating correctly over data due to which you were getting y:null and x:NaN.

    Content inside data is array of objects inside an array i.e. [[{}, {}, {}...]]so you need to iterate accordingly.

    Use this code:

      data.forEach(function(array) {
        array.forEach(function(arrayItem) {
          dataPoints.push({
            y: new Date(arrayItem.source_ts),
            x: Number(arrayItem.renewablesobligationconsumption)
          });
        });
      });
    

    Below is complete working example. Now your dataPoints is ready, you can use it anywhere you want:

    // Fetching the data
    fetch('https://example.com/my/endpoint').then(response => {
      return response.json();
    }).then(data => {
    
      // Generating Data Points
      var dataPoints = [];
    
      data.forEach(function(array) {
        array.forEach(function(arrayItem) {
          dataPoints.push({
            y: new Date(arrayItem.source_ts),
            x: Number(arrayItem.xyzw)
          });
        });
      });
      
     console.log(dataPoints);
    
      var chart = new CanvasJS.Chart("chartContainer", {
        data: [{
          dataPoints: dataPoints,
          type: "line",
        }]
      });
    
      chart.render();
    }).catch(err => {
      throw new Error('Impossible to get data');
    });
    <br/>
    <!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
    
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>