Skip to content

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 string
  • options 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 to
    • true 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) - default false

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

  • arr the array to convert to a csv string
  • quoteStrings a boolean value indicating whether to add quotes to strings or not (default false)
  • delim the 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.