Skip to content

Commit

Permalink
Add logic to wrap booleans when specified.
Browse files Browse the repository at this point in the history
In order to support the use case of keeping Booleans as String values
that can easily be converted back with csv2json, this commit adds a new
option `wrapBooleans` which will allow users a way to make this possible

Fixes #188
  • Loading branch information
mrodrig committed May 20, 2021
1 parent e72fa24 commit f89cff0
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -138,6 +138,8 @@ Looking for examples? Check out the Wiki: [json-2-csv Wiki](https://github.com/m
* `useLocaleFormat` - Boolean - Should values be converted to a locale specific string?
* Default: `false`
* Note: If selected, values will be converted using `toLocaleString()` rather than `toString()`
* `wrapBooleans` - Boolean - Should boolean values be wrapped in wrap delimiters to prevent Excel from converting them to Excel's TRUE/FALSE Boolean values.
* Default: `false`


For examples, please refer to the [json2csv API Documentation (Link)](https://github.com/mrodrig/json-2-csv/wiki/json2csv-Documentation)
Expand Down
3 changes: 2 additions & 1 deletion lib/constants.json
Expand Up @@ -35,7 +35,8 @@
"unwindArrays": false,
"useDateIso8601Format": false,
"useLocaleFormat": false,
"parseValue": null
"parseValue": null,
"wrapBooleans": false
},

"values" : {
Expand Down
3 changes: 2 additions & 1 deletion lib/json2csv.js
Expand Up @@ -362,7 +362,8 @@ const Json2Csv = function(options) {
// then enclose it in quotation marks (wrap delimiter)
if (fieldValue.includes(options.delimiter.field) ||
fieldValue.includes(options.delimiter.wrap) ||
fieldValue.match(crlfSearchRegex)) {
fieldValue.match(crlfSearchRegex) ||
options.wrapBooleans && (fieldValue === 'true' || fieldValue === 'false')) {
// wrap the field's value in a wrap delimiter (quotation marks by default)
fieldValue = wrapDelimiter + fieldValue + wrapDelimiter;
}
Expand Down
19 changes: 19 additions & 0 deletions test/json2csv.js
Expand Up @@ -618,6 +618,25 @@ function runTests(jsonTestData, csvTestData) {
parseValue: () => 'Parsed Value'
});
});

it('should wrap boolean values in wrap delimiters, if specified', (done) => {
converter.json2csv(jsonTestData.emptyFieldValues, (err, csv) => {
if (err) done(err);

// Replace raw boolean values with quoted versions
let expectedCsv = csvTestData.emptyFieldValues
.replace(',"",', ',,')
.replace(/\n"",/g, '\n,')
.replace(/false/g, '"false"')
.replace(/true/g, '"true"');

csv.should.equal(expectedCsv);
done();
}, {
emptyFieldValue: '',
wrapBooleans: true
});
});
});
});

Expand Down

0 comments on commit f89cff0

Please sign in to comment.