Fetch and display JSON data in Chartjs

Updated: 06-Dec-2023 / Tags: Javascript and JSON / Views: 2415 - Author: George

Introduction

In this post we are going to create a small application that fetches data from a JSON file and displays it in a chart using JavaScript and the Chart.js library.

Also the application will give us the option to display the data in various chart types like, bars, lines, doughnuts etc.

Live Demo

I have prepared a live demo so you can see what we are going to build.

The data are fetched from a JSON file. Click on the buttons to see the different chart types displaying the data. Our charts are going to be responsive so we can display them on any screen size.

Project's folder

Let's see the files that we need to create our application.

|-- project-folder/
  |-- data.json
  |-- index.html
  |-- script.js
  |-- styles.css
  • data.json In this file, we have the JSON data.
  • index.html Is our starting page and will display the charts.
  • script.js In this file we are going to write our javascript code.
  • styles.css Is our stylesheet, which is not important for this tutorial, so i am not going through and explain the css code. If you download the source code you will get the whole project including the css file.

The data.json file

Let's s start to code our application starting from the JSON file.

[
	{ "month": "Ian", "income": 1210 },
	{ "month": "Feb", "income": 1920},
	{ "month": "mar", "income": 830 },
	{ "month": "Apr", "income": 1300 },
	{ "month": "Mai", "income": 990 },
	{ "month": "Jun", "income": 1250 }
]

  • In our data.json file we have an array of objects. Every object has a "month", and an "income" property. We will target these properties from the JavaScript file to display their values in our charts.

The Index file

Next we have our index file.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="styles.css">
	<title>Displaying JSON data in Chart.js</title>
</head>
<body>

	<div class="chart">
		<div class="chart_types">
			<button onclick="setChartType('bar')">Bars</button>
			<button onclick="setChartType('line')">Line</button>
			<button onclick="setChartType('doughnut')">Doughnut</button>
			<button onclick="setChartType('polarArea')">PolarArea</button>
			<button onclick="setChartType('radar')">Radar</button>
		</div>
		<canvas id="myChart"></canvas>
	</div>

	<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
	<script src="script.js"></script>
</body>
</html>
	
  • Lets breakdown the code in the index file.
  • In line 6 we have a link to our stylesheet.
    <link rel="stylesheet" href="styles.css">
  • The lines 13-17 contain the buttons that are responsible for changing the chart type.
    <button onclick="setChartType('bar')">Bars</button>
    <button onclick="setChartType('line')">Line</button>
    <button onclick="setChartType('doughnut')">Doughnut</button>
    <button onclick="setChartType('polarArea')">PolarArea</button>
    <button onclick="setChartType('radar')">Radar</button>

    Each button has an onclick event-listener assigned, which will trigger a function named setChartType. This function takes as an argument the type of the chart that we want to display.

    The arguments exactly match the chart types used by the Chart.js library.

  • In line 19 we have the canvas element with an id of "myChart". Chart.js is using the canvas element to render the charts.
    <canvas id="myChart"></canvas>
  • In line 22 we accessing the Chart.js library via a CDN network. Without this script tag nothing will work.
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  • And in line 23 we have a script tag that points to our javascript file.
    <script src="script.js"></script>

The javascript file

Let's examine and explain the code in our JavaScript file using comments. This should make it easier for you to understand what is happening.

/* 
	I will target the canvas element and i will store it in
	the `ctx` variable. 
*/		
let ctx = document.getElementById('myChart');

/*
	Next i will create two global variables, the `myChart` variable
	and the `JsonData` variable. We are going assign to them values that
	we create inside the functions that we will use down the script.
*/
let myChart;
let Jsondata;

/*
	Next we are going to send a get request to the `data.json`
	file to retrieve the file's data.
*/
fetch("data.json")
.then(function(response){
   if(response.status == 200){
      return response.json();
   }
})
.then(function(data){ 
	/*
		Assigning the data from the JSON file to the `jsonData`
		global variable.	
	*/
	Jsondata = data;

	/*
		Calling the `createChart` function to create the chart
		from the json data.
		The function takes two parameters. The first parameter holds
		the json data, and the second the chart type.
		Here we initiating the chart type to `bar`.
	*/
	createChart(Jsondata, 'bar');
});	

/*
	Next we have the createChart function.
*/
function createChart(data, type){
	// Inside the function we create a new instance of the Chart object.
	// The constructor takes the canvas element `ctx`, 
	// as its first argument, and an object with the Chart.js properties.
	myChart = new Chart(ctx, {
		// Setting the chart's type to the `type` parameter.
		type: type, 
		data: {
			
			// Creating an array from the `months` from the json data
			// using the `map` method and assign it to the labels
			// property.
			labels: data.map(row => row.month), 
			
			datasets: [{
				label: '# of Income',
				
				// Creating an array from the `incomes` from the json data
				// using the `map` method and assign it to the data
				// property.
				data: data.map(row => row.income),
				
				borderWidth: 1
		  }]
		},
		options: {
			scales: {
				y: {
					beginAtZero: true
				}
			},
			// Making the chart responsive.
			responsive: true,
			maintainAspectRatio: false,
		}
	});
}

/*
	The `setChartType` function will dynamically change the chart type
	depending on which button we click on in the index file.
*/
function setChartType(chartType){
	// To change the chart type we have first to destroy the current
	// chart object. 
	myChart.destroy();

	// Next we render a new one passing-in, the `Jsondata`
	// and the `chartType` that the button sends.
	createChart(Jsondata, chartType);
}
	

Summary

In this tutorial we saw how to fetch data from a JSON file and display them in a chart using JavaScript and Chart.js.

We also saw how to change the chart type accordingly to the value that each button sends.

Last Words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 644

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal