Created
October 11, 2015 05:10
-
-
Save huttj/72e20b0f7c2a63e6a656 to your computer and use it in GitHub Desktop.
Quick and dirty CSV parsing on the client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<input type="file" id="files" name="files[]" multiple /> | |
<output id="list"></output> | |
<script> | |
var list = document.getElementById('list'); | |
// Some code taken from HTML5 Rocks: | |
// http://www.html5rocks.com/en/tutorials/file/dndfiles/ | |
function handleFileSelect(evt) { | |
// FileList object | |
var files = evt.target.files; | |
var reader = new FileReader(); | |
reader.onloadend = function(evt) { | |
var json = csvToJSON(this.result); | |
console.log(json); | |
addToList(JSON.stringify(json, false, 2)); | |
}; | |
// files is a FileList of File objects. List some properties. | |
var output = []; | |
for (var i = 0, f; f = files[i]; i++) { | |
reader.readAsText(f); | |
} | |
} | |
function csvToJSON(csv) { | |
csv = csv.trim().split(/\r?\n/); | |
var keys = csv[0].split(','); | |
var list = csv.slice(1).map(function (n) { | |
var props = n.split(','); | |
var obj = {}; | |
for (var i = 0; i < keys.length; i++) { | |
obj[keys[i]] = props[i]; | |
} | |
return obj; | |
}); | |
return list; | |
} | |
function addToList(str) { | |
var pre = document.createElement('pre'); | |
pre.textContent = str; | |
list.appendChild(pre); | |
} | |
document.getElementById('files').addEventListener('change', handleFileSelect, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment