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
content
the csv stringoptions
provides the options for the parser
The options
object can have the following fields:
delimeters
a list strings used to separate the columns of the content - default is[',',';']
header
can be set totrue
to 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
quotedFields
which will strip quotes from the data (if present in the content) - defaultfalse
// Parse a CSV string with header row to get an array of objects
// The header:true option tells the parser to use the first row as property names
var csv = Csv.parse('foo;bar\n100;200', {header: true})
The csv
variable will now contain an array of objects, where each object uses the headers as property names:
[
{ foo: 100, bar: 200 }
]
or if there is no header option specified:
// Parse a CSV string without header information to get an array of arrays
// Each line becomes a simple array of values
var csv = Csv.parse('100;200\n300;400', {})
The csv
variable will now contain an array of arrays, with each inner array representing a row:
[
[ 100, 200 ], // First row
[ 300, 400 ] // Second row
]
Stringify
The stringify(arr, quoteStrings, delim)
method will take an array of objects or an array of arrays generate a csv string.
Parameters
arr
the array to convert to a csv stringquoteStrings
a boolean value indicating whether to add quotes to strings or not (defaultfalse
)delim
the delimeter string to separate fields (default','
)
// Convert an array of arrays to a CSV string
var arr1 = [['foo','bar'],[1,2]]; // Array of arrays to convert
var csvStr1 = Csv.stringify(arr1); // Results in "foo,bar\n1,2"
// Convert an array of objects to a CSV string
var arr2 = [{foo: 3, bar: 4}]; // Array of objects to convert
var csvStr2 = Csv.stringify(arr2); // Also results in "foo,bar\n1,2"
Both approaches produce identical CSV strings. The first row serves as headers in both cases.