json-2-csv icon indicating copy to clipboard operation
json-2-csv copied to clipboard

Wrap Delimiter not wrapping values

Open woutersteven opened this issue 1 year ago • 2 comments

I'm expecting (perhaps incorrectly) that double quotes surround every value, but i'm guessing it is only doing so in some cases. My code is as follows:

   const {json2csv} = await import('json-2-csv');
    const csv = json2csv(result.response.value, {
      delimiter: {
        wrap: '"',
        field: ';',
        eol: '\n',
      },
      emptyFieldValue: '',
    });

The CSV is generated, and contains some Arabic, however there are no quotes surrounding the values. Am i doing something wrong, or isn't it possible to force quotes?

I have the following workaround, but was wondering if the plug-in could do it natively.

   const quotedCSV = csv
      .split('\n')
      .map(line =>
        line
          .split(';')
          .map(field => `"${field}"`)
          .join(';'),
      )
      .join('\n');

woutersteven avatar Mar 05 '25 13:03 woutersteven

Hi @woutersteven, great question. The default behavior follows RFC-4180, which doesn't require double quotes around each value, except in specific scenarios (i.e. the value contains a double quote (wrap delimiter) or a comma (field delimiter) in it). This would be relatively simple to add an option for on the json2csv side of things though, and the wrapFieldValueIfNecessary function (https://github.com/mrodrig/json-2-csv/blob/main/src/json2csv.ts#L412-L431) would just need another conditional to handle if the option is set.

I don't have bandwidth to be able to implement this in the near future myself, but I'm open to a pull request for it if you or someone else that's interested in this feature are open to contributing.

mrodrig avatar Mar 06 '25 03:03 mrodrig

Thanks for the information. I'll find some time this week and submit a PR.

woutersteven avatar Mar 11 '25 14:03 woutersteven