Skip to content
Related Articles

Related Articles

Improve Article

D3.js d3-Fetch API

  • Last Updated : 16 Jul, 2020

D3.js is a library built with javascript and particularly used for data visualization. But this is not only, we can also fetch files of different formats such as xml, csv, pdf etc. using d3-Fetch API.

Importing the d3-Fetch API:

<script src = "https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-fetch.v1.min.js"></script>

Syntax: 

d3.csv(filelocation).then(function);

Types of file it can fetch:

  • Blob
  • Buffer
  • CSV
  • DSV
  • Text
  • HTML
  • XML

NOTE:  It is essential to create the file before fetching the file. Otherwise it throw error.



Example 1: 

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width, initial-scale=1.0">
          
        <script src=
            "https://d3js.org/d3.v4.min.js">
        </script>
        <script src=
            "https://d3js.org/d3-fetch.v1.min.js">
        </script>
</head>
  
<body>
    <script>
        d3.text("./fileName.txt").then(function (text) {
  
            // Output: This is from the FileName
            console.log(text);
        });
    </script>
</body>
  
</html>

Output: 
 

Example 2:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width, initial-scale=1.0">
        <script src=
        </script>
        <script src=
        </script>
        <script src=
        </script>
</head>
  
<body>
    <script>
        d3.json("jsonFile.json").then(function (data) {
            console.log(data);
  
            // Extracting values from the data object
            const val = Object.values(data);
  
            // Extracting keys from the data object
            const key = Object.keys(data);
  
            for (let i = 0; i < val.length; i++) {
                console.log(key[i] + ": " + val[i]);
            }
        });
    </script>
</body>
  
</html>

Output: 
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :