← All Exercises
CSV Line Parser with Quoted Fields
intermediatejavascript
Background
CSV quoting rules come from RFC 4180 and trip up naive split-on-comma implementations. Data pipelines that export user text need exactly this state machine.
Problem
Implement a state-machine CSV parser. Fields may be wrapped in double quotes; inside quotes, commas are literal data and a doubled double quote is one literal quote character. Split the input into lines, treat the first line as a header, and parse the rest as rows. Output the header and all rows.
Input
A JSON object {"csv": string} where csv uses \n line separators, no embedded newlines inside quotes, and a header on the first line.Output
A JSON object {"header": string[], "rows": string[][]} with every field as a string.Sample tests
Sample 1
Input: {"csv":"name,age,note\nAlice,30,\"likes tea, and chess\"\nBob,25,\"said \"\"hi\"\""}Expected: {"header":["name","age","note"],"rows":[["Alice","30","likes tea, and chess"],["Bob","25","said \"hi\""]]}Sample 2
Input: {"csv":"a,b\n1,\"\n2,x"}Expected: {"header":["a","b"],"rows":[["1",""],["2","x"]]}Your solution
Learning objective
Write a character-level state machine for a real-world interchange format.