Skip to content

Commit ff514ba

Browse files
mkopinskyknownasilya
authored andcommitted
fix: Handle dates without double-escaping (#189)
1 parent 638245c commit ff514ba

File tree

4 files changed

+22
-1
lines changed

4 files changed

+22
-1
lines changed

lib/json2csv.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,15 @@ function createColumnContent(params, str) {
249249
.replace(/\u2029/g, '\r');
250250
}
251251

252-
if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement);
252+
if (typeof val === 'object') {
253+
// In some cases (e.g. val is a Date), stringifiedElement is already a quoted string.
254+
// Strip the leading and trailing quotes if so, so we don't end up double-quoting it
255+
stringifiedElement = replaceQuotationMarks(stringifiedElement, '');
256+
257+
// If val is a normal object, we want to escape its JSON so any commas etc
258+
// don't get interpreted as field separators
259+
stringifiedElement = JSON.stringify(stringifiedElement);
260+
}
253261

254262
if (params.quotes !== '"') {
255263
stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes);

test/fixtures/csv/date.csv

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
"date"
2+
"2017-01-01T00:00:00.000Z"

test/helpers/load-fixtures.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ var fixtures = [
99
'withoutQuotes',
1010
'withNotExistField',
1111
'quotes',
12+
'date',
1213
'selected',
1314
'reversed',
1415
'tsv',

test/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,16 @@ async.parallel(loadFixtures(csvFixtures), function (err) {
340340
});
341341
});
342342

343+
test('should handle date', function (t) {
344+
json2csv({
345+
data: {'date': new Date("2017-01-01T00:00:00.000Z")}
346+
}, function (error, csv) {
347+
t.error(error);
348+
t.equal(csv, csvFixtures.date);
349+
t.end();
350+
});
351+
});
352+
343353
test('should flatten embedded JSON', function (t) {
344354
json2csv({
345355
data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}},

0 commit comments

Comments
 (0)