Skip to content

Commit

Permalink
fix: Handle dates without double-escaping (#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkopinsky authored and knownasilya committed Jul 25, 2017
1 parent 638245c commit ff514ba
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/json2csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/csv/date.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"date"
"2017-01-01T00:00:00.000Z"
1 change: 1 addition & 0 deletions test/helpers/load-fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ var fixtures = [
'withoutQuotes',
'withNotExistField',
'quotes',
'date',
'selected',
'reversed',
'tsv',
Expand Down
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'}},
Expand Down

0 comments on commit ff514ba

Please sign in to comment.