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
javascript
// 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:

javascript
[
  { foo: 100, bar: 200 }
]

or if there is no header option specified:

javascript
// 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:

javascript
[
  [ 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 string
  • quoteStrings a boolean value indicating whether to add quotes to strings or not (default false)
  • delim the delimeter string to separate fields (default ',')
javascript
// 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.