From ff514ba5fbb1af1cabf85cb0379731f87d6011f9 Mon Sep 17 00:00:00 2001 From: Michael Kopinsky Date: Tue, 25 Jul 2017 17:52:16 -0400 Subject: [PATCH] fix: Handle dates without double-escaping (#189) --- lib/json2csv.js | 10 +++++++++- test/fixtures/csv/date.csv | 2 ++ test/helpers/load-fixtures.js | 1 + test/index.js | 10 ++++++++++ 4 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/csv/date.csv diff --git a/lib/json2csv.js b/lib/json2csv.js index 7729c7cd..764df493 100644 --- a/lib/json2csv.js +++ b/lib/json2csv.js @@ -249,7 +249,15 @@ function createColumnContent(params, str) { .replace(/\u2029/g, '\r'); } - if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement); + if (typeof val === 'object') { + // In some cases (e.g. val is a Date), stringifiedElement is already a quoted string. + // Strip the leading and trailing quotes if so, so we don't end up double-quoting it + stringifiedElement = replaceQuotationMarks(stringifiedElement, ''); + + // If val is a normal object, we want to escape its JSON so any commas etc + // don't get interpreted as field separators + stringifiedElement = JSON.stringify(stringifiedElement); + } if (params.quotes !== '"') { stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes); diff --git a/test/fixtures/csv/date.csv b/test/fixtures/csv/date.csv new file mode 100644 index 00000000..30ee4b81 --- /dev/null +++ b/test/fixtures/csv/date.csv @@ -0,0 +1,2 @@ +"date" +"2017-01-01T00:00:00.000Z" \ No newline at end of file diff --git a/test/helpers/load-fixtures.js b/test/helpers/load-fixtures.js index aa47d6bc..a7ac8a6f 100644 --- a/test/helpers/load-fixtures.js +++ b/test/helpers/load-fixtures.js @@ -9,6 +9,7 @@ var fixtures = [ 'withoutQuotes', 'withNotExistField', 'quotes', + 'date', 'selected', 'reversed', 'tsv', diff --git a/test/index.js b/test/index.js index 96022485..784e6e93 100644 --- a/test/index.js +++ b/test/index.js @@ -340,6 +340,16 @@ async.parallel(loadFixtures(csvFixtures), function (err) { }); }); + test('should handle date', function (t) { + json2csv({ + data: {'date': new Date("2017-01-01T00:00:00.000Z")} + }, function (error, csv) { + t.error(error); + t.equal(csv, csvFixtures.date); + t.end(); + }); + }); + test('should flatten embedded JSON', function (t) { json2csv({ data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}},