Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Project to Convert JSON Objects to CSV File Using json2csv Library in Javascript

Posted on February 14, 2023

 

 

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

 

 

JavaScript
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.

 

 

 

 

Recent Posts

  • Android Java Project to Merge Multiple PDF Documents From Gallery Using iTextPDF Library
  • Android Java Project to Detect System Hardware & System CPU Info & Display inside TextView Widget
  • Android Java Project to Integrate Google OAuth2 Login & Logout System & Save User Info in SharedPreferences
  • Android Java Project to Export Raw Text to PDF Document Using iTextPDF Library
  • Android Java Project to Export Images From Gallery to PDF Document Using iTextPDF Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme