Skip to content

Instantly share code, notes, and snippets.

@oliverfoster
Last active January 29, 2020 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliverfoster/d546b1ecaf6f773801f3b3aefb1c5554 to your computer and use it in GitHub Desktop.
Save oliverfoster/d546b1ecaf6f773801f3b3aefb1c5554 to your computer and use it in GitHub Desktop.
function csvToJSON(data) {
var rows = [['']];
for (var i = 0, l = data.length, char = data[i], wasInSpeechMarks = false, isInSpeechMarks = false; i < l; char = data[++i]) {
if (wasInSpeechMarks && char !== "," && char !== "\n" && char !== "\r") { // skip after speech mark waiting for new column or row
} else if (isInSpeechMarks && char === '"' && data[i+1] !== '"') { // at end of speechmark block
isInSpeechMarks = false;
wasInSpeechMarks = true;
} else if (isInSpeechMarks || char !== '"' && char !== "," && char !== "\n" && char !== "\r") { // is in speechmarks or not a new colum or row
if (isInSpeechMarks && char === '"' && data[i+1] === '"') i++; // is in speechmarks at a double quote
rows[rows.length-1][rows[rows.length-1].length-1] += char; // add character to current cell
} else if (char === '"') { // is at the start of speechmarks
rows[rows.length-1][rows[rows.length-1].length-1] = ''; // remove everything before opening speechmark
isInSpeechMarks = true;
} else { // new colum or row
wasInSpeechMarks = false;
if (char === '\r' && data[i+1] === '\n') i++; // as new colum in windows format, skip character
if (char === ',') rows[rows.length-1].push(''); // add new column
else rows.push(['']); // add new row
}
}
return rows;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment