F# CSV Parsing with FParsec
I needed a .NET CSV parser for work, and since I don’t trust most .NET code I find online I wrote one in F# with FParsec!
This handles both quoted and unquoted cells. It even supports escaped characters (including commas)!
For example,
CODE, EN, FR
HOME_DESCRIPTION, Hello\, welcome to our site!, Bonjour\, bienvenue sur notre site
Will parse to:
[
["CODE", "EN", "FR"],
["HOME_DESCRIPTION", "Hello, welcome to our site!", "Bonjour, bienvenue sur notre site"]
]
You can even mix them if you want:
"CODE", "EN", "FR"
HOME_DESCRIPTION, Hello\, welcome to our site!, "Bonjour, bienvenue sur notre site"
This will parse to the same thing
It even handles cases where there are quotes inside unquoted cells!
Since we’re using FParsec, if the parse fails it will tell you exactly where and why. Here is an excerpt from one of my test cases that fails when there’s a comma missing:
Error in Ln: 4 Col: 19
SOME_CODE,"Herp\,"Derp
^
Expecting: end of file, newline or ','
Have fun!