Welcome to a tutorial on how to read and parse a CSV file into an array or object in Javascript. Need to read a CSV file in your project? Yes, it is possible to do so in modern Javascript. No server-side scripts are required – Read on for the examples!
TABLE OF CONTENTS
READ & PARSE CSV
All right, let us now get into the examples of how to read and parse a CSV file into an array/object in Javascript.
EXAMPLE 1) PARSE CSV INTO AN ARRAY
1A) DUMMY CSV
Joa Doe,joa@doe.com,123456
Job Doe,job@doe.com,234567
Joe Doe,joe@doe.com,345678
Joi Doe,joi@doe.com,456789
Jon Doe,jon@doe.com,987654
"Joy, Doe",joy@doe.com,124578
For this example, we will use this list of dummy users. For the uninitiated, CSV files are nothing more than “plain text with formatting”:
,
Commas are used to denote columns.\r\n
New lines are used to denote rows."Joy, Doe"
If a cell contains a comma, it will be enclosed within double quotes.
1B) THE HTML
<!-- (A) JS -->
<!-- https://github.com/okfn/csv.js/ -->
<script src="csv.min.js"></script>
<script src="1-csv-array.js"></script>
<!-- (B) FILE PICKER -->
<input type="file" accept=".csv" id="demoA">
- We will be using a lightweight library called csv.js to parse the CSV into an array.
- An HTML file input field to select a CSV file.
1C) THE JAVASCRIPT
window.onload = () => {
// (A) FILE PICKER
let picker = document.getElementById("demoA");
// (B) READ CSV FILE
picker.onchange = () => {
// (B1) GET SELECTED CSV FILE
let selected = picker.files[0];
// (B2) READ CSV INTO ARRAY
let reader = new FileReader();
reader.addEventListener("loadend", () => {
// (B2-1) PARSE INTO ARRAY
let csv = CSV.parse(reader.result);
// (B2-2) LOOP THROUGH ROWS & COLS
for (let row of csv) {
for (col of row) {
console.log(col);
}
}
// (B2-3) DONE
// let data = JSON.stringify(data);
// picker.value = "";
});
reader.readAsText(selected);
};
};
This should be pretty self-explanatory:
- (A) Get the HTML file picker field –
let picker = document.getElementById("demoA")
- (B) Use a
let reader = new FileReader()
object to read the selected CSV file. - (B2) But of course, the
reader
will return the entire CSV file as a string. We will have to use the library to parse it into an array –let csv = CSV.parse(reader.result)
.
EXAMPLE 2) PARSE CSV INTO AN OBJECT
2A) DUMMY CSV
Name,Email,Number
Joa Doe,joa@doe.com,123456
Job Doe,job@doe.com,234567
Joe Doe,joe@doe.com,345678
Joi Doe,joi@doe.com,456789
Jon Doe,jon@doe.com,987654
"Joy, Doe",joy@doe.com,124578
Look no further, this is the same example. It only has an additional header row that we will use as the key of the object.
DATA = {
Name : [...],
Email : [...],
Number : [...]
}
2B) THE HTML
<!-- (A) JS -->
<!-- https://github.com/okfn/csv.js/ -->
<script src="csv.min.js"></script>
<script src="2-csv-object.js"></script>
<!-- (B) FILE PICKER -->
<input type="file" accept=".csv" id="demoB">
Once again, it’s the same “load library” and “HTML file picker”.
2C) THE JAVASCRIPT
window.onload = () => {
// (A) FILE PICKER
let picker = document.getElementById("demoB");
// (B) READ CSV FILE
picker.onchange = () => {
// (B1) GET SELECTED CSV FILE
let selected = picker.files[0];
// (B2) READ CSV INTO ARRAY
let reader = new FileReader();
reader.addEventListener("loadend", () => {
// (B2-1) PARSE INTO ARRAY
let csv = CSV.parse(reader.result);
// (B2-2) REARRANGE KEYS & VALUES
let data = {};
for (let [col,key] of Object.entries(csv[0])) {
data[key] = [];
for (let row=1; row<csv.length; row++) {
data[key].push(csv[row][col]);
}
}
console.log(data);
// (B2-3) DONE!
// data = JSON.stringify(data);
// picker.value = "";
});
reader.readAsText(selected);
};
};
Not going to explain this line-by-line, but it’s essentially the same as the previous example.
- (A & B) Get the selected CSV file and read it.
- (B2-1) Parse the CSV string into an array first.
- (B2-2) Loop through the array and rearrange it into an object.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here to download. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
PERFORMANCE ISSUES & LIMITATIONS
At the time of writing, there are seemingly no ways to read CSV files line-by-line with the FileReader
. That is, it will read the entire CSV file into a string all at once. While this works, it will run into performance and memory issues with massive CSV files. So yep, this is one “limitation” to take note of… Until the developers decide to “fix” FileReader
and give it a “read line-by-line” feature.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- File Reader – CanIUse
Well-supported on modern browsers, but not for the ancient Internet Exploders.
LINKS & REFERENCES
- How To Read Files In Javascript – Code Boxx
- Read CSV Files In NodeJS – Code Boxx
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!