How to wrap the contents of all datatype but not only string inside " " using `json2csv` library in node js?

62 Views Asked by At

json2csv only wrapped up the string types inside double quotes (" "). But I want all the contents of different datatype like numbers, boolean, null etc, to be wrapped up in (" ") too.

Below is my piece of code:

function generateCSV(jsonData: any[], fileName: string): void {
  const opts = {
    defaultValue: "",
    quotes: '"',
  };
  const parser = new Parser(opts);
  const csvData = parser.parse(jsonData);
  console.log(csvData);

  fs.writeFile(fileName, csvData, (err) => {
    if (err) {
      console.error("Error saving CSV:", err);
    } else {
      console.log("CSV saved successfully.");
      parentPort?.postMessage("success");
    }
  });

My input data is like this:

[
    {
      name: "Alice",
      age: 28,
      department: "HR",
      contact: "hell",
      phone: "123-456-7890",
      email: "[email protected]",
    },
    {
      name: "Bob",
      age: 32,
      department: "Engineering",
      contact: false,
      email: "[email protected]",
      phone: "987-654-3210",
    },
    {
      name: "Charlie",
      age: null,
      phone: 9876543210,
      department: "Marketing",
    },
];

And my output is like this:

"name","age","department","contact","phone","email"
"Alice",28,"HR","hell","123-456-7890","[email protected]"
"Bob",32,"Engineering",false,"987-654-3210","[email protected]"
"Charlie",,"Marketing","",9876543210,""

The output I expect or want it to be wrapped up all elements:

"name","age","department","contact","phone","email"
"Alice","28","HR","hell","123-456-7890","[email protected]"
"Bob","32","Engineering","false","987-654-3210","[email protected]"
"Charlie","","Marketing","","9876543210",""

Well, I tried other alternative libraries like papaparse and json-2-doc too. But they didn't work as expected too.

I also tried making customFormatter as well but it didn't work too. You can help me by making proper customFormatter too.

1

There are 1 best solutions below

2
traynor On

Use transforms, and pass in your function, which will then turn all values into a string:

Try this:

// turn all values into a string
function myTransformer(item) {
    
    for (const p in item) {
        item[p] = item[p] !== null ? String(item[p]) : '';
    }
    return item;
}

const opts = {
    defaultValue: "",
    quotes: '"',
    transforms: [
        myTransformer
    ]

};