Welcome folks today in this blog post we will be converting json objects to csv
file using json2csv
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i json2csv
And after that you will see the below directory structure of the app is shown below
Basic Example
Now we will be seeing the basic example to convert the array of json
objects to csv
file
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const json2csv = require('json2csv').parse; const fs = require('fs'); // Example JSON data const data = [ { name: 'John Doe', email: 'johndoe@example.com', age: 30 }, { name: 'Jane Smith', email: 'janesmith@example.com', age: 25 }, { name: 'Bob Johnson', email: 'bobjohnson@example.com', age: 40 } ]; // Define fields to include in CSV const fields = ['name', 'email', 'age']; // Convert JSON to CSV const csv = json2csv(data, { fields }); // Write CSV to file fs.writeFile('data.csv', csv, function(err) { if (err) throw err; console.log('CSV file saved!'); }); |
As you can see that in the above code we are importing the json2csv
library and then we are having the array of json objects
and then we are using the json2csv()
method to export it to csv
file.