jsonexport
jsonexport copied to clipboard
add forceTextStrings option to give csv readers a hint to text fields
Status
READY
Description
Quotes string fields so that when importing the csv, it can automatically detect text columns vs numeric columns. This helps a lot with having working sort column on version numbers where 3.1 and 3.11 are not numbers but strings
Hi @patrickdk77
Thanks a lot for this contribution! =)
But i think we already have good support for this use case using the typeHandlers options.
For example, you could write a handle function to convert all object types to string:
const jsonexport = require('jsonexport');
//data
const contacts = {
'a' : Buffer.from('a2b', 'utf8'),
'b' : Buffer.from('other field', 'utf8'),
'x' : 22,
'z' : function(){return 'bad ace'}
};
const convertToString = (anyObject) => String(anyObject)
const options = {
//definitions to type cast
typeHandlers: {
Array: convertToString,
Boolean: convertToString,
Function: convertToString,
Number: convertToString,
String: convertToString,
Buffer: convertToString,
}
};
jsonexport(contacts, options, function(err, csv) {
if (err) return console.error(err);
console.log(csv);
});
This also gives more control, like only do this for Numbers.
Did you try using the typeHandlers? Do you agree its very similar to what forceTextStrings is implementing?
i dont understand how this would enforce a text field ia quoted and a number field is not.
it can control the data in the field but i dont see how this xontrols the use of quotes for the field
If I am reading it right, the parseObject code reads the json and writes the csv values It calls the typeHandler for each field that it reads in, so here the value could be modified It then calls the escape function that adds the quotes aound the field if needed and escapes any quotes or newlines inside the field. I dont see how typeHandler could adjust how the escape function works, since escape is called after the typeHandler.