In this article I will explain with an example, how to read the CSV File and convert its data to JSON Array in jQuery using HTML5 File API.
The CSV file (Comma separated Text file) will be selected in HTML5 FileUpload element and will be read using HTML5 FileReader API.
The read data is split into Rows and a loop is executed over the Rows and the data from each Row is stored into a JSON object and it is added to an Array using jQuery.
Converting CSV File data to JSON Array in jQuery using HTML5 File API
The HTML Markup consists of a FileUpload control (HTML File Input) and a HTML Button.
The CSV file is selected in FileUpload control (HTML File Input) and Upload button is clicked. The Upload button is wired with a jQuery OnClick event handler.
Inside the event handler, first a check is performed to verify whether the file is a valid CSV or a text file. Then a check is performed to make sure whether the browser supports HTML5 File API.
The read data is split into Rows and a loop is executed over the Rows and the data from each Row is stored into a JSON object and it is added to an Array using jQuery.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var customers = new Array();
var rows = e.target.result.split("\r\n");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
if (cells.length > 1) {
var customer = {};
customer.Id = cells[0];
customer.Name = cells[1];
customer.Country = cells[2];
customers.push(customer);
}
}
$("#dvCSV").html('');
$("#dvCSV").append(JSON.stringify(customers));
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
Screenshots
Contents of the CSV file placed on user’s folder
The generated JSON Array
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Downloads