In this chapter, we can learn how to convert JSON data into CSV data and export data as a CSV file there are many ways to do that but I will teach you a simple and clean way to export your JSON data into CSV.


Follow the below steps to convert a JSON file into a CSV file: 


Step 1

Install csv-writer

npm install csv-writer


Example:

code.js

// Import csv-writer
import csvwriter from 'csv-writer'

var createCsvWriter = csvwriter.createObjectCsvWriter

// Passing the column names intp the module
const csvWriter = createCsvWriter({

path: 'data.csv',
header: [

	// Title of the columns (column_names)
	{id: 'id', title: 'ID'},
	{id: 'name', title: 'NAME'},
	{id: 'age', title: 'AGE'},
]
});

// Values for each column through an array
const results = [
{
	id: '10',
	name: 'Rathorji',
	age: 30
}, {
	id: '20',
	name: 'Jhon',
	age: 21
}, {
	id: '30',
	name: 'Crytina',
	age: 20
},{
	id: '40',
	name: 'Varun',
	age: 40
}
	
];
// add data to Writerecords
csvWriter
.writeRecords(results)
.then(()=> console.log('Data uploaded into csv successfully'));


Let’s run your application using the following command 

node code.js


Thanks, May this example will help you.