How To Specify Configurations To Json2csv In Express
According to the docs it's possible to provide configurations e.g include NULL or set default values when parsing JSON to CSV using the json2csv module, but I'm not able to get make it work.
Is this right?
const json2csvParser = new Parser({ fields,defaultValue : "NA",includeEmptyRows : true });
Answer
The default option works if the field is missing from the JSON data or if it is undefined, however it will not replace a null value, we can see this by testing below.
You could potentially pre-process your data to replace nulls with undefined values if you wish this behaviour.
BTW, you can also set defaults for each field, which is very useful by creating an array of field objects like so:
const fields = [{ label: 'car', value: 'car', default: 'carDefault' },
{ label: 'price', value: 'price', default: 'priceDefault' },
{ label: 'color', value: 'color', default: 'colorDefault' } ];
The Porsche and Mercedes colors are populated with the default value below because the field is missing or undefined, the BMW is not since the color is null.
const { Parser } = json2csv;
const fields = ['car', 'price', 'color']
const myCars = [
{
"car": "Audi",
"price": 40000,
"color": "blue"
}, {
"car": "BMW",
"price": 35000,
"color": null
}, {
"car": "Porsche",
"price": 60000
}, {
"car": "Mercedes",
"price": 60000,
"color": undefined
}
];
const json2csvParser = new Parser({ fields, defaultValue : "NA", includeEmptyRows : true });
const csv = json2csvParser.parse(myCars);
console.log("CSV output:");
console.log(csv);
<script src="https://cdn.jsdelivr.net/npm/json2csv"></script>
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error