False value not serialized to 0
Closed this issue · 4 comments
Describe the bug
I'm trying to serialize false value, but the output is always empty. I would expect 0
To Reproduce
import { stringify } from 'csv-stringify';
stringify([
[ '1', '2', '3', '4' ],
[ true, false, 'c', 'd' ]
], function(err, output){
console.log(output)
});
The output is
1,2,3,4
1,,c,d
I would expect
1,2,3,4
1,0,c,d
Additional context
Version 6.5.1
The source is probably here:
I'm not sure about the reason.
Hi @MartinM85, you can configure the serialize behavior with the cast option.
https://csv.js.org/stringify/options/cast/
Here is an example of it in action:
https://github.com/adaltas/node-csv/blob/master/packages/csv-stringify/samples/option.cast.js
This particular example is for numbers, but you can easily adapt this for bools so you can get "1" and "0" instead of "1" and "".
E.g. something like:
stringify(myData, {
cast: {
boolean: function (value) {
return value ? "1" : "0";
},
},
});
Hi @DylanMaptaskr, I've found how to override the serialize behavior, so it's resolved.
Just for curiosity...why is false value serialized as an empty string?
I'm not one of the developers on this project so I can only guess.
My guess would be something to do with the truthiness of strings.
E.g in this statement:
let myBoolean = someString ? true : false;
someString = "0"
will evaluate as true in the above statement
someString = ""
will evaluate as false in the above statement
why is false value serialized as an empty string
I had to make a choice and it doesn't seem right to serialize false
with a value. It seems very right to serialize false
to empty, that way it work the other way around, empty is deserialized to false. At the time, the question for me was more about how to serialize true
. I didn't want something like "true"
because it is language specific, thus the choice of "1"
.
Pretty sure, this is also probably at the same time when I implemented the cast.boolean
option (git history would confirm), providing more flexibility on that default behavior.