Csv
The Csv module can be used for parsing, manipulating and generating comma-separated files.
Parse
The parse method takes a csv formatted string and returns an array of objects or arrays - one for each row in the string. There is also a parseFile variant which is identical to the parse method except that it takes a filename as its first argument.
Parameters
contentthe csv stringoptionsprovides the options for the parser
The options object can have the following fields:
delimetersa list strings used to separate the columns of the content - default is[',',';']headercan be set totrueto indicate that a header is present in the first line of the content or you can set it to an- array of strings to provide the header manually (the first line is treated as normal data) or you can
- leave it or or set it to
null(the default) which will cause the parsed result to be an array of arrays instead of an array of objects
quotedFieldswhich will strip quotes from the data (if present in the content) - defaultfalse
Examples
javascript
var csv = Csv.parse('foo;bar\n100;200', {header: true})The csv variable will now contain:
javascript
[
{ foo: 100, bar: 200 }
]or if there is no header:
javascript
var csv = Csv.parse('100;200\n300;400', {})The csv variable will now contain:
javascript
[
[ 100, 200 ],
[ 300, 400 ]
]Stringify
The stringify(arr, quoteStrings, delim) method will take an array of objects or an array of arrays generate a csv string.
Parameters
arrthe array to convert to a csv stringquoteStringsa boolean value indicating whether to add quotes to strings or not (defaultfalse)delimthe delimeter string to separate fields (default',')
Example
javascript
var arr1 = [['foo','bar'],[1,2]];
var arr2 = [{foo: 3, bar: 4}];
var csvStr1 = Csv.stringify(arr1);
var csvStr2 = Csv.stringify(arr2);csvStr1 and csvStr2 will now both have the value foo,bar\n1,2.
