Creating Live Updating Charts from JSON Data API

Here is an example on creating Live Updating Chart using JSON Data API. Generally it’s a good idea to fetch data via ajax rather than embedding in the web page. JSON data is easy to parse and generate the chart accordingly.

Here are the steps for creating Live Charts using JSON Data.

We will be using following JSON format (2 dimensional array) in this example:

 [[1,12],[2,7],[3,6],[4,6],[5,9],[6,13],[7,12],[8,15],[9,14],[10,18]]

As a first step we need get data by making an AJAX call (we use jQuery) and then parse the same to convert the data into CanvasJS DataPoints – like {x: 5, y: 6}. Please refer to Working with Data for more information. Then pass the dataPoints to the chart and call chart.render().

Step1:

Get data from external JSON source and render the chart.

var dataPoints = [];
$.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=10&type=json", function(data) {  
    $.each(data, function(key, value){
        dataPoints.push({x: value[0], y: parseInt(value[1])});
    });
    chart = new CanvasJS.Chart("chartContainer",{
        title:{
            text:"Live Chart with dataPoints from External JSON"
        },
        data: [{
        type: "line",
        dataPoints : dataPoints,
        }]
    });
    chart.render();
    updateChart();
});

Step2:

For every second call updateChart method. Each time updateChart is called, it gets data from JSON, adds it to dataPoint and calls chart.render()

function updateChart() {
   $.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=" + (dataPoints.length + 1) + "&ystart=" + (dataPoints[dataPoints.length - 1].y) + "&length=1&type=json", function(data) {
       $.each(data, function(key, value) {
           dataPoints.push({
               x: parseInt(value[0]),
               y: parseInt(value[1])
           });
      });
      chart.render();
      setTimeout(function(){updateChart()}, 1000);
   });
}

Finalising

To summarize, in order to create a Live charts using JSON Data from external source, we need to get data from external JSON using jquery, push into dataPoints for plotting the chart.

Below is the compilation of final code.

Try Editing The Code

If you have any questions, please feel free to ask in our forums.Ask Question