Back to Blog
Technicalcsvrfc-4180papaparse

Why Parsing CSV Is Harder Than It Looks (RFC 4180)

Why CSV is harder to parse than it looks: what RFC 4180 actually says, quoting and escaping, a parser state machine, delimiter detection, ragged rows, and the byte order mark.

LoopalooPublished April 24, 202611 min read

Every engineer who has touched a data pipeline has written line.split(',') at least once, shipped it, and watched it explode the moment a customer uploaded a file with a comma inside a quoted field. CSV is the format everyone assumes they understand and almost nobody implements correctly. It looks like "values, separated, by commas," and for the trivial cases it really is that simple. The trouble is that the real world produces files where a single cell contains a comma, a line break, a double quote, or all three at once, plus a byte-order mark at the very front that you cannot even see.

There is a specification, RFC 4180, published in 2005, that pins down what a "well formed" CSV file looks like. It is short, about six pages, and you can read it in ten minutes. But RFC 4180 is descriptive rather than enforced: nothing stops Excel, a database export, or a hand-edited file from violating it, and they routinely do. So a good parser has to honor the spec for files that follow it and also degrade gracefully for the enormous population of files that almost follow it.

This post walks through the rules that make CSV harder than it looks, shows exactly where a naive split falls apart, and uses PapaParse, a widely used open-source CSV parser for JavaScript, to show how a real parser deals with each case.

What RFC 4180 actually says

The grammar in RFC 4180 is small. Stripped to the parts that matter:

  • Records are separated by CRLF (\r\n).
  • Fields within a record are separated by commas.
  • A field may be enclosed in double quotes.
  • If a field is quoted, it may contain commas, CRLFs, and double quotes. A literal double quote inside a quoted field is represented by two double quotes ("").
  • An optional header line, with the same format as the rest, may appear first.

The fourth rule is the one that breaks naive parsers. A quoted field is its own little world: until the closing quote, commas and newlines are just text, not structure. Consider this perfectly legal file:

id,name,note
1,"Smith, John","He said ""hello""
and then left"

That is three columns and (counting the header) two records. The note field of the data row contains He said "hello", then a line break, then and then left. To a human reading the raw bytes it looks like three lines of text. To a correct parser the last two lines are one record, and its final field spans both of them.

Why split(',') is doomed

Here is the function almost everyone writes first:

function naiveParse(text) {
  return text
    .trim()
    .split('\n')
    .map(line => line.split(','));
}

Run it on the example above and watch it produce garbage:

BugWhat happens
Embedded comma"Smith, John" splits into "Smith and John", turning a 3-column row into 4 columns
Embedded newlineThe note field is cut in half; "and then left" becomes a phantom extra row
Escaped quotes""hello"" is preserved literally instead of being unescaped to "hello"
Surviving quote charsThe literal " characters stay in your data because nothing strips the enclosing quotes

You cannot patch this with a smarter regular expression either. A regex that "matches commas not inside quotes" needs to track quote state across the whole input, and once you are tracking state across an arbitrary span you have written a parser, not a regex. (The classic "CSV regex" you find on Stack Overflow handles quoted commas but still falls over on embedded newlines, because it assumes one record per line.) The only correct approach is a scanner that knows, at every character, whether it is currently inside a quoted field. Real CSV libraries, PapaParse included, are built that way, even when they speed things up by jumping ahead to the next quote or delimiter instead of stepping through every byte.

The state machine, in plain terms

A correct CSV reader walks the input one character at a time and tracks a small amount of state: are we inside a quoted field or not, and was the previous character a quote. The rules are roughly:

  • Outside quotes, a comma ends the field and a newline ends the record.
  • A quote at the start of a field opens a quoted field; now commas and newlines are literal text.
  • Inside a quoted field, a quote might be the end of the field, or it might be the first half of an escaped "". You decide by peeking at the next character: another quote means "emit one literal quote and stay inside"; anything else means "the field is closed."

In RFC 4180 the escape character and the quote character are the same character, which is confusing the first time you see it. There is no backslash escaping in standard CSV; the only way to put a quote inside a quoted field is to double it. PapaParse mirrors this in its options: quoteChar defaults to ", and escapeChar defaults to whatever quoteChar is.

A minimal implementation of those three rules fits in about forty lines:

function parseCsv(text, delimiter = ',') {
  const rows = [];
  let row = [];
  let field = '';
  let inQuotes = false;

  for (let i = 0; i < text.length; i++) {
    const ch = text[i];

    if (inQuotes) {
      if (ch === '"' && text[i + 1] === '"') {
        field += '"'; // escaped quote: keep one, skip the other
        i++;
      } else if (ch === '"') {
        inQuotes = false; // closing quote
      } else {
        field += ch; // delimiters and newlines are plain text here
      }
    } else if (ch === '"' && field === '') {
      inQuotes = true; // opening quote at the start of a field
    } else if (ch === delimiter) {
      row.push(field);
      field = '';
    } else if (ch === '\r' || ch === '\n') {
      if (ch === '\r' && text[i + 1] === '\n') i++; // CRLF counts once
      row.push(field);
      rows.push(row);
      row = [];
      field = '';
    } else {
      field += ch;
    }
  }

  if (inQuotes) throw new Error('Unterminated quoted field');
  if (field !== '' || row.length > 0) {
    row.push(field);
    rows.push(row);
  }
  return rows;
}

It is deliberately small. It takes the delimiter as given instead of detecting it, it reads the whole string at once instead of streaming, and it throws on an unclosed quote instead of trying to recover. But it gets the hard part right: feed it the Smith example and the comma inside "Smith, John", the doubled quotes, and the line break inside the note all land in the correct fields.

Delimiter detection: comma is a lie

The "C" in CSV stands for comma, but a large fraction of CSV files in the wild are not comma-delimited. The biggest reason is locale: in many European locales the decimal separator is a comma (1,5 means one and a half), so Excel exports those files using a semicolon as the field delimiter to avoid ambiguity. Tab-separated files (.tsv) are common in bioinformatics and database dumps. Pipe-delimited (|) files show up in legacy systems.

If you hardcode comma, a semicolon-delimited file parses as a single giant column. So a good parser guesses. PapaParse, when you do not pass a delimiter, runs delimiter detection: it parses a small preview of the input (the first ten rows) once per candidate delimiter and scores each one. Its default candidate set is comma, tab, pipe, semicolon, plus two ASCII control characters (the record and unit separators). The winner is the delimiter that produces the most consistent field count from row to row, with the added requirement that it yield more than one field per row on average. If nothing qualifies, it falls back to comma and records an error.

You decide how much of this happens. Passing a delimiter switches detection off; leaving it unset (any empty value counts as unset) switches it on; and the delimitersToGuess option narrows the candidate list when you know a file is, say, either comma or semicolon. Whatever the parser settles on is reported back in meta.delimiter, which is worth logging when files arrive from many different sources.

// Let the parser guess, then check what it picked
const guessed = Papa.parse(text, { skipEmptyLines: true });
console.log(guessed.meta.delimiter); // ';' for a typical European Excel export

// Or state what you already know
const explicit = Papa.parse(text, { delimiter: ';', skipEmptyLines: true });

Explicit is better than inferred because automatic detection is a heuristic, not a guarantee. A file with one column and no delimiters at all is ambiguous (it never clears the "more than one field per row" bar), and a file where the first few preview rows happen to contain a stray semicolon can skew the score. When you know the delimiter, telling the parser is always more reliable than making it guess.

Ragged rows: when records do not agree on width

RFC 4180 says "each line should contain the same number of fields throughout the file." The word "should" is doing a lot of work there. Real files have ragged rows constantly: a trailing comma that adds a phantom empty column, a row with a missing value and no placeholder, a hand-edited file where someone deleted a cell.

A strict parser would reject the whole file. That is almost never what a user wants when they drag a slightly broken export into a browser tool. PapaParse reports these as non-fatal problems rather than aborting. In header mode, where the header row defines the expected width, field-count problems show up in results.errors with the type FieldMismatch and a code of TooFewFields or TooManyFields. The data still comes back; you are just told which rows looked off. Without a header there is no expected width, so no FieldMismatch is reported and you have to compare row lengths yourself.

The errors array is where you decide how broken a file really is. A simple triage looks like this:

const result = Papa.parse(text, { header: true, skipEmptyLines: true });

const fatal = result.errors.filter(e => e.type === 'Quotes');
const ragged = result.errors.filter(e => e.type === 'FieldMismatch');
const noDelimiter = result.errors.some(e => e.code === 'UndetectableDelimiter');

if (fatal.length > 0) {
  // A broken quote: the fields after it cannot be trusted
  throw new Error(fatal[0].message);
}
if (ragged.length > 0) {
  console.warn(ragged.length + ' rows have the wrong number of fields');
}
// noDelimiter usually means a one-column file, which parsed fine

The error types PapaParse emits map cleanly onto "how badly is this broken":

TypeMeaningSensible treatment
QuotesA quoted field was malformed or never closedFatal: stop and report
DelimiterNo delimiter could be detected (code UndetectableDelimiter)Usually a one-column file that parsed correctly with the comma fallback: treat it as a note
FieldMismatchA row has too few or too many fieldsWarning: load anyway and say which rows

An unclosed quote earns the harsh treatment because of what it does to everything after it. From the stray quote onward, every comma and newline is read as text, so the rest of the file can collapse into one enormous field. A missing comma on row 4,000, by contrast, should not stop you from looking at the other 3,999 rows. The Loopaloo CSV Viewer & Editor draws the line in the same place: an unclosed quote stops the load and tells you why, while a ragged file loads in full with a note saying how many rows differ in width from the first.

The invisible byte: BOM and encoding

This one costs people hours. A file saved as "UTF-8 with BOM" (Excel's "CSV UTF-8" format writes one, and so do many Windows and .NET tools) begins with three bytes, EF BB BF, the UTF-8 encoding of the byte-order mark. Those bytes are invisible in every editor, but they are real, and they attach themselves to the very first field.

The classic symptom: your header row is id,name,email, you parse with header: true, and then row.id is undefined. The first column name is not "id" at all. It is "\uFEFFid", with an invisible BOM glued to the front, and that string does not equal "id". You can stare at a console.log for twenty minutes before you think to check character codes.

PapaParse strips a leading BOM from string input, which removes the most common version of this bug for files that reach the parser as text. There is a layer below that, though, that no CSV parser can fully solve: the bytes have to be decoded into a JavaScript string first. In a browser that usually means FileReader.readAsText or File.text(), both of which decode as UTF-8 by default. A file that is actually Windows-1252 will arrive with replacement characters (�) where its accented letters used to be, and the reverse mistake, UTF-8 read as Windows-1252, produces the familiar mojibake of é where é should be. Either way the damage happened at the decode step, before the parser ever saw the text. Encoding detection from raw bytes is a separate problem from CSV grammar, and a hard one; the pragmatic answer is to standardize on UTF-8 for anything you control and re-save legacy files with a known encoding.

A worked example that hits every trap

Here is a file that exercises embedded delimiters, embedded newlines, escaped quotes, a ragged row, and a semicolon delimiter all at once:

id;label;description
1;"Widget, deluxe";"Ships in 2-3 days"
2;"He said ""ok""";"Multi-line
description here"
3;"Orphan";

A correct parser, with the delimiter detected as ;, produces:

idlabeldescription
1Widget, deluxeShips in 2-3 days
2He said "ok"Multi-line + newline + description here
3Orphan(empty)

Several things had to go right. The semicolon was chosen over the comma despite "Widget, deluxe" containing a comma. The doubled quotes in row 2 collapsed to a single literal quote. The newline inside row 2's description stayed inside the field instead of starting a new record. And row 3's trailing empty value was preserved rather than dropped. A split gets every one of those wrong, and a real parser gets every one right.

Practical rules of thumb

If you take nothing else from RFC 4180, take these:

  • Never parse CSV with split, a regex, or string slicing. Use a real parser. The edge cases are not exotic; they are in your first hundred customer files.
  • When you know the delimiter and whether there is a header row, pass them explicitly. Detection is a fallback, not a feature to depend on.
  • Treat field-count mismatches as warnings, not crashes, unless your downstream logic really does require uniform width.
  • Normalize to UTF-8 early, and remember that a BOM is real bytes. Strip it when you read, or it poisons your first column name. Write one when you produce a file a spreadsheet will open, or the spreadsheet may guess the encoding and get accented text wrong.
  • When you write CSV, quote any field that contains a comma, a quote, or a newline, and double the quotes inside it. Treat that as a minimum rather than a preference: a writer set to "no quotes" must still quote a field that holds the delimiter, or the file cannot be read back. And separate records with CRLF, as section 2.1 of the RFC specifies; nearly every reader also accepts a bare LF, but CRLF is the safe default.

Try it on Loopaloo

If you just want to load a file and see whether it parses cleanly, the CSV Viewer & Editor shows the fatal-versus-warning distinction described above, so you can tell a broken quote from a merely ragged row. The CSV Formatter & Validator is the place to experiment with delimiters and quoting styles when a file is almost but not quite consistent; even its "No quotes" style still quotes any field that would otherwise break the file. And when you need structured output, the CSV to JSON Converter applies the RFC 4180 quoting and escaping rules, so embedded commas and newlines come through as real string values rather than mangled fields. All three run entirely in your browser, and your file never leaves your machine.

Related Tools

Related Articles