How to create a chart from JSON data using Fetch API in JavaScript?


In this article, we are going to explore on how to create a chart after fetching the JSON data. To fetch JSON data we use fetch() method of Fetch API. We will first fetch the data and once the data is available we will feed it into the system to create a chart. The Fetch API provides a simple interface for accessing and manipulating HTTP requests and responses.

Syntax

const response = fetch(resource [, init])

Parameters

  • resource − This is the resource path from where the data is fetched.

  • init − It defines any extra options such as headers, body, etc.

Approach

The steps can be defined as below −

Step 1 − We will fetch the data from some remote server by calling the fetch function.

Step 1 − Once the data is available we will feed it into the system.

Step 3 − With the help of the Chart JS library we will form the chart for this.

Example #1

In the below example, we fetch the data from the remote server and then create the desired chart. The US population data is fetched from the server.

# index.html

 Live Demo

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
   </script>
   <title>Population Chart</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <div style="width: 800, height: 600">
      <canvas id="bar-chart">
      </canvas>
   </div>
<script>
   getData();
   async function getData() {
      const response = await fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population');
      const data = await response.json();
      console.log(data);
      length = data.data.length;
      console.log(length);
      labels = [];
      values = [];
      for (i = 0; i < length; i++) {
         labels.push(data.data[i].Year);
         values.push(data.data[i].Population);
      }
      new Chart(document.getElementById("bar-chart"), {
         type: 'bar',
         data: {
            labels: labels,
            datasets: [
               {
                  label: "Population (millions)",
                  backgroundColor: ["#3a90cd",
                     "#8e5ea2",
                     "#3bba9f",
                     "#e8c3b9",
                     "#c45850",
                     "#CD9C5C",
                     "#40E0D0"],
                  data: values
               }
            ]
         },
         options: {
            legend: { display: false },
            title: {
               display: true,
               text: 'U.S population'
            }
         }
      });
   }
</script>
</body>
</html>

Output

On successful execution of the above program, it will generate a bar chart the of U.S. population. You can hover over the bar to see the population for a particular year. It can also be seen in the below gif image

Updated on: 21-Apr-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements