CSV documentation

Allows parsing and stringifying of CSV data.

import * as csv from '@cipscis/csv'; import { stringify, parse } from '@cipscis/csv'; import { stringify } from '@cipscis/csv/stringify'; import { parse } from '@cipscis/csv/parse';

stringify

stringify(data: any[][], options?: StringifyOptions): string

Converts a 2D Array into a CSV string.

Stringify converts most falsey values into empty cells. undefined, '', and [] are all treated this way. null and false, however, are converted into string representations when stringifying CSV data.

If you need to maintain a value of undefined, '', or [] when stringifying your CSV data, convert it to a string first (e.g. 'undefined')

Arguments

data: any[][]

A 2D Array to convert into a CSV string.

options?: StringifyOptions

(Optional) an object containing any of these properties:

transpose?: boolean

If set to true, swap rows and columns before saving.

sanitise?: boolean

If set to true, prepend each cell starting with '=' | '-' | '+' | '@' with a tab character. This prevents spreadsheet software like Excel from trying to execute code.

This option should be used when saving any data to a CSV that may include data from an untrusted source, such as user-generated data.

Examples

Output:
Input:

parse

parse(csvString: string): string[][] parse<T>(csvString: string, mapper: (cell: string) => T): T[][]

Converts a CSV string into a 2D Array.

parse will throw a SyntaxError if the string it is passed is malformed in one of these ways:

  • Unclosed quote
  • Closed quote not followed immediately by separator
  • Rows of unequal lengths

All values are converted to strings. If you need to convert them further, for example changing the strings 'true' and 'false' to boolean values, you can do this in separate code after the fact.

Arguments

csvString: string

A CSV string to convert to a 2D Array.

mapper?: (cell: string) => T

A function that takes a string containing the value of a single CSV cell, and returns the value it should be mapped to.

If no mapper function is passed, parse will always return a 2D Array of strings. If a mapper function is passed, the 2D Array will be of the type returned by the mapper function.

Examples

Output:
Input: