function parseCSV(str){
var csvArr = str.replace(/","/igm,",,,").split("\n");
//takes input CSV string and replaces all the separators
//with triple commas to prevent confusion with commas
//that may be part of a record and not a seperator,
//then splits at every newline to create an array of records
var key = csvArr[0].split(',,,');
//the key is the first line, which is used to map
//the other records
var csvRecords = new Array();
//main array for storing data
csvArr.pop();
(csvArr[csvArr.length-1]) ? csvArr.shift() : false
//first entry in csvArr is the key, remove it
//last entry is typically a blank string, remove it
for(var i=0;i<csvArr.length;i++){
//traverses all valid records in csvArr
csvRecords[i] = { };
var rec = csvArr[i].split(',,,');
//rec is set anew for each row in the csv file
for(var x=0;x<csvArr[i].length;x++){
csvRecords[i][key[x]] = rec[x];
//for each row in csvArr, set the obj property
//to the correct entry from the key array
//and set the property value to the correct
//value from rec
}
}
return csvRecords;
//all done
}
A Simple Function That Parses a CSV String Into JSON
Subscribe to:
Posts (Atom)
Twitter
Facebook
Flickr
RSS