CSV parsing is hard. There's not a strict standard, so each implementation is a little different. And when I say CSV, I don't necessarily mean literal "comma-separated values" -- the delimiter could be any character. It's also common to see tabs and pipes as separators.
I work with a lot of delimited text data, and too often I find CSV files that are malformed. Usually quotes are not escaped, or quotes are missing around a field that has special characters like newlines, delimiters, or another quote.
But typical CSV parsers are guilty, too. We can do better.
So here's a way to easily parse CSV with Javascript while keeping the process efficient and error-free as possible, even if you encounter malformed content.
I work with a lot of delimited text data, and too often I find CSV files that are malformed. Usually quotes are not escaped, or quotes are missing around a field that has special characters like newlines, delimiters, or another quote.
But typical CSV parsers are guilty, too. We can do better.
So here's a way to easily parse CSV with Javascript while keeping the process efficient and error-free as possible, even if you encounter malformed content.
Just use the "Parse" jQuery Plugin
Get the Parse jQuery Plugin on GitHub. It does the hard work for you. If you don't want to have the jQuery dependency, just pull out the "Parse" function from within it. At its core, this plugin doesn't actually need jQuery. (But it's distributed as a jQuery plugin for convenience and publicity.)
The "Parse" jQuery plugin is very easy to use:
results = $.parse(csvString, {
delimiter: ",",
header: true,
dynamicTyping: true
});
The second argument (the config) is optional, but the defaults have been specified here for documentation.
To access a value, say, if you're iterating the resulting rows:
results.rows[i]["Field Name"]
For more instructions on how to use the plugin—it's very easy, I promise—check out the README on GitHub.