CSV is harder than it looks: quoting, delimiters, encodings and converting to JSON

Why splitting on commas breaks real CSV files: quoting, line breaks in fields, semicolon delimiters, BOMs and what to decide when converting to JSON.

Data · 7 min read · Published

CSV, comma-separated values, looks like the simplest data format there is: one record per line, fields separated by commas. That simplicity is misleading. Almost every hand-written CSV parser works on the first test file and then breaks on a real export from a spreadsheet, a CRM or a bank. This guide covers the rules that actually govern CSV, the variations you will meet in practice, and the decisions you have to make when converting it to JSON.

Why splitting on commas fails

The obvious approach is line.split(','). It fails as soon as a field contains a comma, which happens constantly with addresses, names written as "Last, First", and numbers formatted with thousands separators. To handle this, CSV lets a field be wrapped in double quotes, and inside quotes a comma is just text:

name,city,amount
"Smith, Jane",London,"1,250.00"

That is three fields, not five. And once quotes are allowed, you need a way to write a quote inside a quoted field. CSV does it by doubling: "She said ""hi""" holds the text She said "hi".

Line breaks inside fields

The rule that breaks the second wave of parsers: a quoted field may contain a line break. Spreadsheet cells with multi-line text, such as notes, addresses and descriptions, are exported this way. So you cannot even split the file into lines first. One record can span several lines, and the only way to know is to track whether you are inside quotes while reading character by character.

That is why reliable parsers are small state machines rather than chains of split calls. The format was eventually written down in RFC 4180 (2005), which describes the quoting rules above. Many producers follow it loosely, so a good parser has to be a bit forgiving.

Not always commas

In much of Europe and South America, the comma is the decimal separator: 3,14. Spreadsheet software in those locales exports "CSV" with semicolons between fields so the numbers survive. Tab-separated files (TSV) are also common, and pipe-separated files turn up in older data exports.

A practical way to detect the delimiter is to count how often each candidate (, ; tab |) appears in the first line, ignoring anything inside quotes, and pick the most frequent. The CSV to JSON converter does this automatically and lets you override the choice.

Line endings and the invisible BOM

Files produced on Windows end lines with \r\n, and others with \n. A parser that only splits on \n leaves a stray \r at the end of the last field of every row, which shows up as a mysterious failed comparison in your code.

Excel also likes to save UTF-8 CSV with a byte order mark, three invisible bytes (EF BB BF) at the very start of the file. If they are not stripped, the first column header becomes \uFEFFname instead of name. It looks identical when printed, but row.name is undefined. If your first column alone seems to be missing, check for a BOM.

Older exports may not be UTF-8 at all. Windows-1252 or regional encodings turn accented characters into garbage like é when read as UTF-8. If that happens, re-save the file as UTF-8 from the program that created it.

Everything is a string

CSV has no types. 42, true, 2024-09-04 and empty fields are all just text. Converting to JSON forces a decision about each:

  • Numbers. Turning "42" into 42 is usually what you want, but it destroys values that only look numeric. ZIP codes like 02134 lose their leading zero, long IDs and credit-card-like numbers lose precision beyond 15–16 digits, and phone numbers get mangled. Keep such columns as strings.
  • Empty fields. Decide whether an empty cell becomes "", null, or is omitted. Each means something different to the code that consumes the JSON.
  • Dates. Leave them as strings unless you know the format. 04/09/2024 is 4 September in most of the world and 9 April in the US.

Headers, duplicates and shape

When the first row holds column names, each record can become a JSON object keyed by header: {"name": "Smith, Jane", "city": "London"}. This is the most readable shape and the one most APIs expect.

Two headers with the same name are a trap. A naive conversion writes the second value over the first, and data disappears without any error. A safer converter keeps both, for example by giving the second key a suffix. The opposite case, a file with no header row, is better turned into an array of arrays, where every row is a list of values in column order. This shape is also more compact for large files, because the keys are not repeated on every row.

Ragged rows

Real files sometimes have rows with more or fewer fields than the header, typically from a stray unquoted comma or a truncated export. After converting, scan for records with missing or extra keys: values may have shifted into the wrong columns. Open the file at that row. The cause is almost always an unescaped delimiter or quote.

Checklist

  • Use a real parser that handles quotes, doubled quotes and line breaks inside fields.
  • Check the delimiter. Semicolon-separated files are normal in many locales.
  • Strip the BOM and normalise \r\n.
  • Keep ID-like and leading-zero columns as strings.
  • Watch for duplicate headers and rows with the wrong number of fields.
  • Validate the resulting JSON before you ship it. A JSON formatter will point to the exact position of any syntax error.