A Complete Guide to Parse CSV File with JS

Photo of author

Parsing a CSV (Comma Separated Values) file is a common task for developers, as it’s a popular format for exchanging data between different systems. In JavaScript, you can parse a CSV file using built-in methods, libraries, or both. In this article, we will go through the different methods for parsing a CSV file in JavaScript and the pros and cons of each approach.

parse csv file with javascript

How to Parse CSV File With JS

There are different methods to parse any CSV file with JavaScript. Let’s discuss all of them in detail –

Method 1: Using The Built-in split() Method

The simplest way to parse a CSV file in JavaScript is to use the built-in split() method. Using a defined delimiter—in this case, a comma—this method divides a string into an array. Here’s how it works:

var csvString = “Name,Age,City\nJohn,30,New York\nJane,25,London”;

var rows = csvString.split(“\n”);

var headers = rows[0].split(“,”);

var data = [];

for (var i = 1; i < rows.length; i++) {

  var obj = {};

  var values = rows[i].split(“,”);

  for (var j = 0; j < headers.length; j++) {

    obj[headers[j]] = values[j];

  }

  data.push(obj);

}

console.log(data);

In the code above, we first split the CSV string into an array of rows using the split(“\n”) method. Then, we split the first row (which contains the headers) into an array of headers using the split(“,”) method. Finally, we loop through the remaining rows and create an object for each row, where the keys are the headers, and the values are the values from that row.

Pros

  • Simple and easy to understand.
  • No need to include any additional libraries.

Cons

  • Limited error handling.
  • The data has limited handling of quotes, new lines, and other special characters.
  • Performance can be slow for large CSV files.

Parse CSV

Method 2: Using A Library

Several JavaScript libraries are available for parsing CSV files, including Papa Parse, csv-parse, and fast-csv. These libraries provide additional features such as error handling, special character handling, and performance optimizations, making them a better option for complex CSV parsing tasks.

For this article, we will use Papa Parse as an example. Here’s how to use it:

var csvString = “Name,Age,City\nJohn,30,New York\nJane,25,London”;

Papa.parse(csvString, {

  header: true,

  complete: function(results) {

    console.log(results.data);

  }

});

The code above passes the CSV string to Papa.parse() method and an options object. Since the header option is true, it will consider the CSV file’s first row to be its header. The complete option is a callback function that is called once the parsing is complete, and it returns the results in the data property of the results object.

Pros

  • Additional error handling and special character handling.
  • Improved performance for large CSV files.
  • Easy to use.

Cons

  • Requires an additional library.
  • It can have a larger file size due to the library size.

Method 3: Using The ‘FileReader’

The FileReader object is a part of the File API and allows us to read the contents of a file as a binary string or text. To parse a CSV file using FileReader, we first need to get a reference to the file using an input element and the change event. Here’s an example:

<input type=”file” id=”fileInput”>

<script>

let fileInput = document.getElementById(“fileInput”);

fileInput.addEventListener(“change”, function() {

  let file = this.files[0];

  let reader = new FileReader();

  reader.onload = function() {

    let csv = reader.result;

    // parse the csv data

  };

  reader.readAsText(file);

});

</script>

In the code above, we first get a reference to the input element using its id attribute. Then, we attach a change event listener to the input element, which fires when a file is selected. When the event fires, we get a reference to the first file in the files array and create a new FileReader object.

Next, we attach an onload event listener to the FileReader object, which gets called when the file successfully loads. In the onload event, we get the file’s contents as a string using the result property and store it in the csv variable.

Parsing CSV File

Now that we have the CSV data as a string, we can parse it using the split() method or a library, such as Papa Parse.

Here’s an example of parsing the CSV data using the split() method:

reader.onload = function() {

  let csv = reader.result;

  let rows = csv.split(“\n”);

  let headers = rows[0].split(“,”);

  let data = [];

  for (let i = 1; i < rows.length; i++) {

    let obj = {};

    let values = rows[i].split(“,”);

    for (let j = 0; j < headers.length; j++) {

      obj[headers[j]] = values[j];

    }

    data.push(obj);

  }

  console.log(data);

};

In the code above, we first split the CSV string into an array of rows using the split(“\n”) method. Then, we split the first row (which contains the headers) into an array of headers using the split(“,”) method. Finally, we loop through the remaining rows and create an object for each row, where the keys are the headers, and the values are the values from that row.

See also: Demystifying HTML No-Cache: How To Implement And Improve Performance

Conclusion

Parsing a CSV file using the FileReader object is a powerful method, as it allows us to read and parse the contents of a file directly in the browser. 

Leave a Comment