import csv file and convert to json - jQuery
Demo and code for how to import CSV file and convert to json
by Athil
Posted on 22 Jun 2019 Category: jQuery
Views: 4407
Here I am going to show how we can import CSV file to HTML using Jquery and convert to JSON string.
Download sample csv file
DEMO
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo for converting CVF file to json</title>
</head>
<body>
<h1> Demo for converting CVF file to json</h1>
<input type="file" id="fileUploadCSV"/>
<input type="button" value="Upload csv" id="btnUpload" />
<div id="DivJson"></div>
<div id="add" style="margin-top:200px;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- DemoBanner1 -->
<ins class="adsbygoogle"
style="display:inline-block;width:970px;height:90px"
data-ad-client="ca-pub-5750437455820212"
data-ad-slot="4021804683"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br/>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- demobanner2 -->
<ins class="adsbygoogle"
style="display:inline-block;width:970px;height:90px"
data-ad-client="ca-pub-5750437455820212"
data-ad-slot="5498537881"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</body>
<script type="text/javascript" src="js/jquery.min.js" >
</script>
<script>
$(function () {
var csv = $("#fileUploadCSV").val();
$("#btnUpload").bind("click", function () {
debugger;
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;//regex for Checking valid files csv of txt
if (regex.test($("#fileUploadCSV").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var rows = e.target.result.split("\r\n");
if(rows.length>0){
var first_Row_Cells = splitCSVtoCells(rows[0], ","); //Taking Headings
var jsonArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
//Converting to json and json string to div
$("#DivJson").html(JSON.stringify(jsonArray));
}
}
reader.readAsText($("#fileUploadCSV")[0].files[0]);
}
else {
alert("This browser does not support HTML5.");
}
} else {
alert("Select a valid CSV File.");
}
});
});
function splitCSVtoCells(row, separator) {
return row.split(separator);
}
</script>
</html>
Related Articles
export HTML table to excel - Javascript
convert JSON object to json string - javascript
Import CSV to HTML Table - jQuery
Removing rows from HTML table - jQuery
Adding rows to HTML table - Jquery