convert json to csv in javascript

To convert JSON data to CSV format in JavaScript, we can use the csv-writer package. First, we need to install it using npm:

index.tsx
npm install csv-writer
23 chars
2 lines

Then, we can use the following code to convert the JSON data to CSV format:

index.tsx
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

// JSON data to be converted to CSV
const jsonData = [
  {name: 'John', surname: 'Doe', age: 35},
  {name: 'Jane', surname: 'Doe', age: 28},
  {name: 'Jim', surname: 'Smith', age: 42}
];

// Define the CSV writer
const csvWriter = createCsvWriter({
  path: 'output.csv',
  header: [
    {id: 'name', title: 'Name'},
    {id: 'surname', title: 'Surname'},
    {id: 'age', title: 'Age'}
  ]
});

// Write the JSON data to CSV
csvWriter.writeRecords(jsonData)
  .then(() => {
    console.log('Conversion successful');
  })
  .catch((error) => {
    console.log(`Conversion failed: ${error}`);
  });
666 chars
28 lines

In this example, we define the JSON data to be converted to CSV format as an array of objects. We then define the CSV writer with the createCsvWriter function from the csv-writer package, specifying the path to the output file and the headers for the CSV file.

Finally, we use the writeRecords function of the CSV writer to write the JSON data to the output CSV file. The result of the conversion will be a CSV file with the same data as the input JSON array.

gistlibby LogSnag