Skip to content

Instantly share code, notes, and snippets.

@robinraju
Created August 4, 2016 12:11
Show Gist options
  • Save robinraju/417692e661cce73efa831d10e73a6793 to your computer and use it in GitHub Desktop.
Save robinraju/417692e661cce73efa831d10e73a6793 to your computer and use it in GitHub Desktop.
Convert CSV document to JSON, using jquery
<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// The event listener for the file upload
document.getElementById('txtFileUpload').addEventListener('change', upload, false);
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
// Method that reads and processes the selected file
function upload(evt) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csvData = event.target.result;
//convert to JS array
//data = $.csv.toArrays(csvData);
var items = $.csv.toObjects(csvData);
var jsonobject = JSON.stringify(items);
alert(jsonobject);
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
}
});
</script>
</head>
<body>
<div id="dvImportSegments" class="fileupload ">
<fieldset>
<legend>Upload your CSV File</legend>
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
</fieldset>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment