Skip to content

How to format values using json2csv in javascript?

I’m using json2csv v5.0.6 for a small project and I wanted to format some values using custom formatters so I get a clean CSV file.

However, I can’t seem to make the formatters work. I have one number formatter and one string formatter that are supposed to be called upon parsing. Here’s a sample test file that reproduces this behaviour, with two simple formatters:

// test.js
const json2csv = require("json2csv")

const data = [{ name: "John", age: 20 }, { name: "Jessica", age: 32 }]

const customNumberFormatter = () => {
    return (value) => {
        return "0"
    }
}

const customStringFormatter = () => {
    return (value) => {
        return value[0]
    }
}

const csvOpts = {
    delimiter: "|",
    formatters: {
        number: customNumberFormatter,
        string: customStringFormatter,
    },
}

const parser = new json2csv.Parser(csvOpts)
const csv = parser.parse(data)
console.log(csv)

// console output
"name"|"age"
"John"|20
"Jessica"|32

// expected output
"name"|"age"
"J"|0
"J"|2

According to the documentation, the following should work, but it does not. So I’m probably doing something wrong but I have not been to figure out what.

Answer

You have to use the alpha version : [email protected]

The last released version has some issue with formatters : https://github.com/zemirco/json2csv/issues/521 (they are not exported)

And you also have to call your formatters functions

const csvOpts = {
    delimiter: "|",
    formatters: {
        number: customNumberFormatter(),
        string: customStringFormatter(),
    },
}