Search code examples
node.jsjsoncsvnpmjson2csv

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 });

Solution

  • 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>