Splitting a CSV on newline and comma feels obvious. I built exactly that parser, then ran 5 test cases against it. Only 1 passed. Full run in this Short: https://youtu.be/Mp89iYCmfGU
What the naive split got wrong
The split-on-comma parser handles the happy path: plain fields, no quotes, Unix line endings. Real CSV files are not like that. Four of the five test cases broke it:
- Quoted commas: a comma inside a quoted field is data, not a separator. The naive split cut the field in half.
- Escaped quotes: a double quote inside a quoted field is written as two quotes. The naive split treated it as the end of the field.
- Newlines inside a field: a quoted field can span lines. Splitting on newline shredded the record.
- Windows line endings: CRLF left a stray carriage return glued to the last field of every row.
What passed instead
A small state machine parser walked the input character by character, tracking whether it was inside quotes. It passed 8 of 8 tests, covering the four cases above plus the combinations of them. The rules of CSV are simple, but they are rules about state, not about splitting.
The rule
Never parse CSV with split. The format looks flat and is not. Not tested here: huge files and other encodings, both of which bring their own problems. Use a maintained CSV library.
Watch the run
The real terminal output is in the Short: https://youtu.be/Mp89iYCmfGU (narration is AI-generated; the test output is from a real run). The full build, a 17-line parser, is here: https://youtu.be/zdCNzOnxUv4
Subscribe to Ship Stack AI on YouTube and tell me in the comments what to build and break next.
Top comments (0)