Last active
August 7, 2016 09:35
-
-
Save codekraft-studio/9a05f17672967402e5e9d79eb753575b to your computer and use it in GitHub Desktop.
javascript function to parse csv string into array of objects (demo: http://www.codekraft.it/demos/parsecsv)
This file contains 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
/** | |
* Parse a csv string to array of objects | |
* optionally enclosed by quotes | |
* delimited by user selectable character | |
*/ | |
function parseCSV(string, delimiter) { | |
var lines = string.split(/\r\n|\n/), // get all the lines | |
colnames = [], // the columns names array | |
result = []; // the result array | |
if( !lines.length ) { return; } | |
delimiter = delimiter || ','; | |
var valueReg = new RegExp( | |
"(?!\\s*$)\\s*" + // exlude empty spaces | |
"(?:'([^'\\\\]*(?:\\\\[\\S\\s][^'\\\\]*)*)'|" + // enclosed by '' | |
"\"([^\"\\\\]*(?:\\\\\[\\S\\s][^\"\\\\]*)*)\"|" + // enclosed by "" | |
"([^" + delimiter + "'\"\\s\\\\]*(?:\\s+[^" + delimiter + "'\"\\s\\\\]+)*))\\s*" + // not enclosed | |
"(?:" + delimiter + "|$)", // empty | |
"g" // search globally in string | |
); | |
// get the property name | |
lines[0].replace(valueReg, function (m0,m1,m2,m3) { | |
if( m1 !== undefined ) { colnames.push(m1); } | |
else if( m2 !== undefined ) { colnames.push(m2); } | |
else if( m3 !== undefined ) { colnames.push(m3); } | |
else { colnames.push(''); } // empty element | |
}) | |
// for each line push new object | |
for (var i = 1; i <= (lines.length-1); i++) { | |
var k = 0; | |
var obj = {}; | |
lines[i].replace(valueReg, function (m0,m1,m2,m3) { | |
if( m1 !== undefined ) { obj[colnames[k]] = m1; } | |
else if( m2 !== undefined ) { obj[colnames[k]] = m2; } | |
else if( m3 !== undefined ) { obj[colnames[k]] = m3; } | |
else { obj[colnames[k]] = ''; } // empty element | |
k++; | |
}) | |
result.push(obj); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment