How to read CSV with JavaScript?

How to read CSV with JavaScript?

CSV files are text files that contain comma-separated values. Thus rising the name comma-separated values(CSV). In CSV files each row consists of one instance or record of data. Each line or record may have more than one feature or column or field separated by commas. For example, let’s see the data of students’ marks – “Name, Class, Roll no, Marks”. All are comma separated. Now, let’s explore how to read CSV file in Javascript with an example in deep.

Introduction

JavaScript abbreviated as JS is a programming language. Along with HTML and CSS, It is the widely used scripting language for frontend web development. It can be used for both front-end(client-side) as well as back-end (server-side) development. It is also used by some non-browsing environments like Node.js.

By default, Javascript can not read CSV files as those files are in comma-separated format. So, you need to convert the CSV files into a unique format that can be interpreted by JS.

There is one more format named “Javascript object notation(JSON)”. It can simply parse(convert) the data into native objects in JS. It is very similar to CSV, but it supports Hierarchical data. Unlike CSV, JSON is twice larger in size. Hence, for now, JSON is the best data format for data exchange. There are so many APIs that directly convert the JSON into native JavaScript objects.

Thus, javascript has multiple libraries that can be used to read CSV files. Let’s explore them one by one.

Approaches of reading CSV files in JavaScript

Read CSV files by using the D3.js library

You can use the D3.js library, to read the CSV file in javascript.D3.js is a javascript library used for manipulating data documents, visualizations, etc in javascript.

Now let’s explore an example of reading CSV files in Javascript using D3.js.

<!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="style.css" />
    <title>Read CSV file with JS</title>
</head>

<body>
    <form id="testForm">
      <input type="file" id="UploadFile" accept=".csv" />
      <br />
      <input type="submit" value="submit" />
    </form>
    <script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
    <script>
      const testForm = document.getElementById("testForm");
      const csvDataFile = document.getElementById("UploadFile");
  
      testForm.addEventListener("submit", function (e) {
        e.preventDefault();
        const input = csvDataFile.files[0];
        const reader = new FileReader();
  
        reader.onload = function (e) {
          const text = e.target.result;
          const csvData = d3.csvParse(text);
          document.write(JSON.stringify(csvData));
        };
  
        reader.readAsText(input);
      });
    </script>
  </body>

</html>
Code language: HTML, XML (xml)

In line 17, we have imported the D3.js library. Then, we read the content of the CSV file using the FileReader object from D3.js on CSV file upload.

The csvParse function from D3.js is used to convert the CSV content we read into JSON.

Reading CSV files by using the Papa parse library

Similarly, Papa parse is also a javascript library. it is the fastest and most powerful CSV parser. it is used to convert CSV to JSON and JSON to CSV.

let’s see an example of how to read a CSV file in javascript using papa parser.

<!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="style.css" />
    <title>Read CSV file with JS</title>
</head>

<body>
    <input type='file' id="UploadFile" accept=".csv">

    <button id="uploadsuccess">file uploaded</button>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/papaparse.min.js"></script>

    <script>
        const csvData=[];
        const uploadsuccess=document.getElementById("uploadsuccess").
            addEventListener("click", () => {
                Papa.parse(document.getElementById('UploadFile').files[0], {
                    download: true,
                    header: true,
                    skipEmptyLines: true,
                    complete: function (answer) {
                        console.log("hi");
                        for (i=0; i<answer.data.length; i++) {
                            csvData.push(answer.data[i].APFD);
                        }
                        console.log(csvData);
                    }
                });
            });
    </script>
</body>

</html>
Code language: HTML, XML (xml)

The code sets up an event listener on the uploadsuccess button, which will parse the selected CSV file when the button is clicked. The Papa.parse function uses the Papa Parse library to parse the CSV file and store the data in the csvData array. The data is logged to the console when the parsing is complete.

The Papa parse library provides many other options for customizing the parsing process, such as specifying the delimiter, handling errors, and transforming the data. Be sure to check out the documentation for more information.

Conclusion

So, now you know why is it necessary to convert CSV into JSON while reading CSV in javascript. CSV works better with small data files but JSON is lightweight and it simply parses data into native JS objects. JSON also works better for large datasets.

Besides, JS there are some more programming languages that have started using JSON objects as data exchangers. I hope this blog served good introduction to reading CSV files in javascript.

I hope this helps! Let me know if you have any further questions regarding how to read CSV file in javascript.

Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far