Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle dates without double-escaping #189

Merged
merged 1 commit into from
Jul 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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