Data and text · Medium · 20 min

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));
Console output appears here (console.log).

Go deeper: the RFC 4180 reference →

This in production, with your data? Let's talk for 15 minutes →