JavaScriptFundamental (ES6), part 1
Parse CSV with quoted fields in JavaScript
120 parse CSV with quoted fields
hardParse CSV properly: fields wrapped in double quotes may contain commas, newlines and doubled quotes standing for one literal quote, and rows may end with CRLF or LF. Walk the text a character at a time with a single quoted flag, then turn the rows into objects keyed by the header. Show what text.split does to the same input.
Stuck? Three hints, smallest first
- 1. One boolean is enough state. Inside quotes, a comma and a newline are ordinary characters; outside, they end a field and a row.
- 2. A doubled
""inside a quoted field is one quote and stays inside it, so check the NEXT character before deciding a quote closed the field. - 3. After the loop, flush whatever is still in hand — otherwise a file with no trailing newline loses its last row.
const parseCsv = (text) => {
const rows = [];
let row = [];
let field = '';
let quoted = false;
let i = 0;
while (i < text.length) {
const ch = text[i];
if (quoted) {
if (ch === '"' && text[i + 1] === '"') { field += '"'; i += 2; continue; }
if (ch === '"') { quoted = false; i += 1; continue; }
field += ch; i += 1; continue;
}
if (ch === '"') { quoted = true; i += 1; continue; }
if (ch === ',') { row.push(field); field = ''; i += 1; continue; }
if (ch === '\n' || ch === '\r') {
if (ch === '\r' && text[i + 1] === '\n') i += 1;
row.push(field); rows.push(row); row = []; field = ''; i += 1; continue;
}
field += ch; i += 1;
}
if (field !== '' || row.length) { row.push(field); rows.push(row); }
return rows;
};
const toObjects = ([header, ...body]) =>
body.map((cells) => Object.fromEntries(header.map((key, i) => [key, cells[i] ?? ''])));
const csv = [
'name,lga,crates,note',
'"Adebayo, Tunde",Ikeja,2,"said ""come early"""',
'Ngozi Okafor,Surulere,1,',
'"Musa Bello",Kano,3,"two lines:\nthe second"',
].join('\r\n');
const rows = parseCsv(csv);
const records = toObjects(rows);
const naive = csv.split('\n')[1].split(',').length;
console.log('rows :', rows.length, '| cells per row:', rows.map((r) => r.length));
console.log('record :', records[0]);
console.log('naive :', naive, 'cells for a line that has 4 fields');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('four rows, header included, and no phantom row at the end', rows.length, 4);
test('a comma inside quotes belongs to the field', rows[1][0], 'Adebayo, Tunde');
test('a doubled quote unescapes to one', rows[1][3], 'said "come early"');
test('a trailing comma leaves a real empty field behind', rows[2], ['Ngozi Okafor', 'Surulere', '1', '']);
test('a newline inside quotes stays in the value', rows[3][3].split('\n'), ['two lines:', 'the second']);
test('CRLF is consumed as one row break, so no stray carriage returns', rows.flat().some((c) => c.includes('\r')), false);
test('the header turns the rows into records, all four the same width', [records[0].lga, new Set(rows.map((r) => r.length)).size], ['Ikeja', 1]);
test('splitting on commas gets that same line wrong', naive, 5);
test('and everything parsed is a string: crates is text until you convert it', typeof records[1].crates, 'string');
CSV looks like a one-liner and is not. split(',') breaks on the first quoted comma, and split('\n') breaks on the first quoted newline — both of which appear in real address and note columns constantly. A character walk with one quoted flag is the smallest thing that is actually correct, and it is about twenty lines.
Three details are where hand-written parsers usually leak. The doubled quote has to be checked before the closing quote, or ""come early"" ends the field early. CRLF must be treated as one break, or every last cell carries an invisible \r that ruins comparisons later. And the flush after the loop is what keeps the final row when the file has no trailing newline — while the guard on it, field !== '' || row.length, is what stops a file that does end in a newline from gaining an empty row.
Every value out of a parser like this is a string. crates is '2', not 2, and an empty cell is '', not null — conversion and meaning are the next layer's job, and keeping them out of the parser is what lets it stay this small.