CSVStringify for Node.js

IssuesGitHub

Option relax_quotes

Preserve the quote characters found inside a field without quoting it, as long as nothing else requires quotes.

By default, a field containing a quote character is surrounded by quotes and its interior quotes are escaped, for example say "hi" is written as "say ""hi""". It is aligned with RFC 4180, section 2, rule 5, which states “If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.”. With relax_quotes, the field is written as is, say "hi".

Quoting is still applied when it is required to preserve the structure of the record:

  • the field contains a delimiter;
  • the field contains a record delimiter;
  • the field starts with a quote character, leading whitespaces being ignored, otherwise it would be read back as a quoted field.

The option does not disable explicit quoting. The quoted, quoted_string and quoted_match options still quote the fields they select, and their interior quotes are escaped. It applies to custom and multi-character values of the quote option. It is also accepted as a field-level option returned by the cast functions.

Note, the generated output does not comply with RFC 4180, which forbids quotes inside unquoted fields. Parsers must be lenient to read it back, for example with the relax_quotes option of the parser.

Example

In the relax quotes example, the first field is written without quotes. The second field is quoted because it contain a delimiter. The last field is quoted because it starts with a quote character.

import assert from "node:assert/strict";
import { stringify } from "csv-stringify/sync";

const output = stringify(
  [['relax "quotes"', "I,contain,delimiters", '"I"contain"quotes"']],
  {
    relax_quotes: true,
  },
);

assert.equal(
  output,
  'relax "quotes","I,contain,delimiters","""I""contain""quotes"""\n',
);

About

The Node.js CSV project is an open source product hosted on GitHub and developed by Adaltas.