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 CSV File to JSON File Using csvtojson Library in Javascript

Posted on January 1, 2023

Welcome folks today in this blog post we will be converting csv to json file using csvtojson library in node.js using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to install the below library using the below command as shown below

 

 

npm i csvtojson

 

 

And now we need to make the index.js file and copy paste the following code

 

 

index.js

 

 

JavaScript
1
2
const csvToJson = require('csvtojson');
const fs = require('fs')

 

 

As you can see at the very top we are importing the csvtojson module and also we are importing the fs module. And now we need to create the data.csv file and copy paste the same csv code as shown below

 

 

 

 

 

JavaScript
1
2
3
4
5
6
csvToJson().fromFile('data.csv').then(jsonObj => {
    // Print the JSON object to the console
    console.log(jsonObj);
 
    fs.writeFileSync("result.json",JSON.stringify(jsonObj))
});

 

 

As you can see that we are calling the csvToJson() module and inside it we are calling the fromFile() method to load the input csv file called data.csv and then we are converting the csv file to an array of json objects. And it returns the promise we are handling that using the then statement and inside it we are saving the result as json file using the fs module. We are using the JSON.stringify() method to convert javascript objects to json strings as shown below

 

 

 

 

 

Full Source Code

 

 

JavaScript
1
2
3
4
5
6
7
8
9
const csvToJson = require('csvtojson');
const fs = require('fs')
 
csvToJson().fromFile('data.csv').then(jsonObj => {
    // Print the JSON object to the console
    console.log(jsonObj);
 
    fs.writeFileSync("result.json",JSON.stringify(jsonObj))
});

 

Recent Posts

  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Android Java Project to Download Random Image From Unsplash Using OkHttp & Picasso Library & Display it
  • 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