Parse a CSV with quotes
Before indexing data for RAG you have to read it correctly. A split(',') breaks on the first name that contains a comma.
Write parseCSV(text). The first row is the header; return an array of objects, one per row, with the columns as keys and the values as strings.
Support double-quoted fields that contain commas, escaped quotes written as "" inside a quoted field, \n and \r\n line endings, and a trailing empty line.
The variable SAMPLE holds a small model catalogue.
Challenges 0/4
- Reads simple rows with their header
- Keeps commas inside quotes
- Turns "" into a quote
- Accepts \r\n and a trailing empty line
function parseCSV(text) {
// walk the text character by character and track whether you are inside quotes
const [header, ...rows] = text.trim().split('\n').map((line) => line.split(','));
return rows.map((r) => Object.fromEntries(header.map((h, i) => [h, r[i]])));
}
console.log(parseCSV(SAMPLE));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
Exports from an ERP, a bank or a spreadsheet arrive as CSV, and one company name with a comma or one note with quotes is enough for split(',') to shift every column in that row. The result is not an error, it is worse: amounts in the name column, which then get indexed and which the model quotes with full confidence. A state-machine parser fits in thirty lines and is the first thing to check when a RAG over tabular data gives odd answers. The whole document load is in local RAG with n8n and Ollama.
Go deeper: the RFC 4180 reference →
This in production, with your data? Let's talk for 15 minutes →