A simple CSV parser in JavaScript for the browser (and nodejs)
- Parse CSV to 2-dimension String array
- Specify column names or use the first row as column names
- Custom delimeter, quote character and row delimeter
See test.js
Construct a CSVParser. A CSVParser hold some parser states.
options is an object that can have 3 properties: 'delim', 'quote', 'rowdelim'
Example:
varparser=newCSV.CSVParser('a\tb\tc',{delim:'\t',quote:'"',rowdelim:'\r\n'});while(parser.hasNext()){varrow=parser.nextRow();// do something with row}Every time you call nextRow, the parser will parse next portion of input. This allows you parse only front part of a string with the remainder untouched. You can stop anywhere.
All high-level APIs are implemented by the low-level API in a few lines. See bottom part of csv.js
If specified, use columns as column names. Otherwise use the first row.
- runtime: no
- test: nodejs
node test.js
firefox test.htm
csv.js can be used with:
- browser
- nodejs
- AMD / CMD / require.js
This implementation is compliant to RFC4180, except for the default line delimeter: this implementation use \n, but RFC4180 states it should be \r\n.
Use the following code if you want strict RFC4180 behavior:
CSV.DefaultOptions.rowdelim = '\r\n';
This is a PEG (Parsing Expression Grammar) parser, written in recursive descent style.
The PEG I use is taken from lpeg's homepage (in Lua):
field='"' * ((lpeg.P(1) -'"') +lpeg.P'""')^0*'"' +
(1-lpeg.S',\n"')^0record=field* (',' *field)^0* (lpeg.P'\n' +-1)