CSV looks simple until you actually have to parse it. Commas inside quoted fields, escaped quotes, and linebreaks inside cells all trip up naive parsers. Here's what to watch for when converting CSV to JSON.
1. Don't Split on Commas Alone
A field like "Smith, John" contains a comma inside quotes. A naive split(',') will break that value into two columns. Proper CSV parsing needs to track whether you're inside a quoted field before treating a comma as a column separator.
2. Handle Escaped Quotes
CSV escapes a literal double quote inside a quoted field by doubling it: "She said ""hello""". Your parser needs to recognize "" as one literal ", not the end of the field.
3. Watch for Multi-line Cells
Spreadsheet exports (Excel, Google Sheets) often produce quoted fields containing an actual newline character. If your parser treats every \n as a row break, these rows will silently truncate mid-record — a common source of "missing data" bugs.
4. Normalize Header Casing and Types
CSV has no type system — every value is a string. Decide up front whether numeric-looking columns (IDs, prices) should be coerced to numbers downstream, since the raw JSON output will keep them as strings unless you convert them.
5. Validate Row Length Consistency
Malformed exports sometimes have rows with fewer or more columns than the header. Decide whether to pad missing fields, drop the row, or throw an error — silently misaligning columns produces JSON that looks valid but is wrong.