I needed to import CSV files into a JavaScript program and couldn't find any good way to do it, so I ported an ActionScript snippet written by Marcin.
// Feed this function an entire CSV file in a string. I used Scripting.FileSystemObject
// on Windows to do this.
function parseCSV(data) {
var values = new Array();
var inQuotes = 0;
var ptr = 0;
var rowValues = new Array();
var dataLength = data.length;
var thisValue = "";
while(ptr <= dataLength) {
var c = data.charAt(ptr);
if(c == "," && inQuotes) {
// if we hit a comma and we're not in quotes then that's the end of the value,
// so store and reset.
rowValues.push(thisValue);
thisValue = "";
} else if(c == "\"" && inQuotes) {
// if we've hit quotes and we're not in existing quotes then enter quote mode
inQuotes = true;
} else if(c == "\"" && inQuotes) {
// if we've hit quotes and we're in quotes then first we check if the next
// character is a quote, in which case we output a quote to the value, otherwise
// we exit quotes mode.
if(ptr + 1 < dataLength && data.charAt(ptr+1) == "\"") {
thisValue += "\"";
ptr++;
} else {
inQuotes = false;
}
} else if((c == "\n" || c == "\r" || ptr == dataLength) && inQuotes) {
// If we hit a new line (or the end of the file) then push the current value and
// start a new row
if(c == "\r") ptr++; // skip the \n if this is a file with DOS line endings
if(thisValue = "") {
rowValues.push(thisValue);
thisValue = "";
}
if(rowValues.length > 0) {
values.push(rowValues);
}
rowValues = new Array();
} else {
// default is to just add the character to the output
thisValue += c;
}
ptr++; // move the pointer along
}
return(values);
}
// This function converts a two-dimensional array into an array of hashes.
// This is useful for CSV files where the first line contains column names.
// After running data through arrayToHash(parseCSV(data)) you'll be able to
// do var content = csv[0]['fieldname'];
function arrayToHash(arr) {
var newHash = new Array();
for (var line in arr) {
if (line == 0) continue;
var curLine = new Array();
for (col in arr[line]) {
curLine[arr[0][col]] = arr[line][col];
}
newHash[line - 1] = curLine;
}
return(newHash);
};