Advertisement
  1. Code
  2. Coding Fundamentals
  3. AJAX

Parsing a CSV File With JavaScript

Scroll to top
Final product imageFinal product imageFinal product image
What You'll Be Creating

The CSV (Comma Separated Values) file format is a popular way of exchanging data between applications. In this quick tip, we’ll learn how JavaScript can help us visualize the data of a CSV file.

Creating a CSV File

To begin with, let’s create a simple CSV file. To do this, we’ll take advantage of Mockaroo, an online test data generator. Here’s our file:

Initial-CSV-FileInitial-CSV-FileInitial-CSV-File

Converting a CSV File Into an HTML Table

Now that we’ve generated the file, we’re ready to parse it and build an associated HTML table.

As a first step, we’ll use jQuery’s ajax function to retrieve the data from this file:

1
2
	  $.ajax({
3
        url: 'csv_data.csv',
4
        dataType: 'text',
5
      }).done(successFunction);

Assuming the AJAX request is successful, the successFunction is executed. This function is responsible for parsing the returned data and transforming them into an HTML table:

1
2
	  function successFunction(data) {
3
        var allRows = data.split(/\r?\n|\r/);
4
        var table = '<table>';
5
        for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
6
          if (singleRow === 0) {
7
            table += '<thead>';
8
            table += '<tr>';
9
          } else {
10
            table += '<tr>';
11
          }
12
          var rowCells = allRows[singleRow].split(',');
13
          for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
14
            if (singleRow === 0) {
15
              table += '<th>';
16
              table += rowCells[rowCell];
17
              table += '</th>';
18
            } else {
19
              table += '<td>';
20
              table += rowCells[rowCell];
21
              table += '</td>';
22
            }
23
          }
24
          if (singleRow === 0) {
25
            table += '</tr>';
26
            table += '</thead>';
27
            table += '<tbody>';
28
          } else {
29
            table += '</tr>';
30
          }
31
        } 
32
        table += '</tbody>';
33
        table += '</table>';
34
        $('body').append(table);
35
      }

The idea is to convert each of the CSV rows into a table row. With that in mind, let’s briefly explain how the code above works:

  • First, we use a regex to split the AJAX response, and thus separate the CSV rows.
  • Then, we iterate through the CSV rows and split their data fields.
  • Finally, we loop through the data fields and create the corresponding table cells.

Furthermore, to get a better understanding of this code, consider the following visualization:

CSV-RepresentationCSV-RepresentationCSV-Representation

At this point, it’s important to clarify why we used the /\r?\n|\r/ regex to split the CSV rows.

As you probably already know, there are different representations of a newline across operating systems. For example, on Windows platforms, the characters representing a newline are \r\n. That said, by using the regex above, we’re able to match all those possible representations.

In addition, most text editors allow us to choose the format for a newline. Take, for instance, Notepad++. In this editor, we can specify the desired format for a document by navigating to this path:

Notepad++-EOLNotepad++-EOLNotepad++-EOL

To illustrate it, consider our file. Depending on the format we choose, it would look like this:

CSV-EOLCSV-EOLCSV-EOL

Adding Styles to the HTML Table

Before we look at the resulting table, let’s add a few basic styles to it:

1
2
	  table {
3
        margin: 0 auto;
4
        text-align: center;
5
        border-collapse: collapse;
6
        border: 1px solid #d4d4d4;
7
      }
8
    
9
      tr:nth-child(even) {
10
        background: #d4d4d4;
11
      }
12
    
13
      th, td {
14
        padding: 10px 30px;
15
      }
16
    
17
      th {
18
        border-bottom: 1px solid #d4d4d4;
19
      }     
20
      

Here’s the generated table:

Generated-TableGenerated-TableGenerated-Table

How to Parse a CSV File With the Papa Parse Library

In this section, we’ll see how you can use the Papa Parse library to parse a CSV file in the blink of an eye! Papa Parse is a really powerful CSV parser which provides you with a lot of configuration options, and you could use it for really big CSV files as well.

The Papa Parse library is available on npm, and if you don’t want to use npm, you can download the official Papa Parse npm package from unpkg instead.

How It Works

The following example demonstrates how easy it is to parse a CSV string.

1
2
	var results = Papa.parse(data); // data is a CSV string

The results variable holds the following contents.

Papa Parse resultsPapa Parse resultsPapa Parse results

As you can see, Results.data holds an array of all the rows. If there are any errors during parsing, they will be in Results.errors. Finally, you can use Results.meta to access meta information about the CSV string.

On the other hand, if you want to directly parse a local CSV file, you can pass a JavaScript File object:

1
2
Papa.parse(fileInput.files[0], {
3
    complete: function(results) {
4
        console.log(results);
5
    }
6
});

And you can also pass in the URL to a remote CSV file:

1
2
Papa.parse(url, {
3
    download: true,
4
    complete: function(results) {
5
        console.log(results);
6
    }
7
});

Apart from basic parsing, Papa Parse provides a lot of other features like:

  • streaming large files (so you can process them line by line)
  • reverse parsing (to emit CSV from a JavaScript object)
  • jQuery integration
  • and more

I encourage you to explore this library since it’s really powerful and easy to use!

Conclusion

In this short article, we went through the process of converting a CSV file into an HTML table. Of course, we could have used a web-based tool for this conversion, but I think that it’s always more challenging to achieve this by writing your own code.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.