| by Arround The Web | No comments

How to Convert Comma-Separated CSV to JSON in Node.js?

A CSV(comma-separated values) file, stores simple, flat, and tabular data(number and text) separated by default delimiter “,(comma)”. On the other hand, JSON(JavaScript Object Notation) is the common data format in programming languages that stores and manages complex, object-oriented, and nested data. The latter format i.e., JSON comes into effect when the users need to utilize the simple CSV file content in the JSON format to use that content in modern web applications and APIs.

This guide will demonstrate the complete procedure to convert comma-separated CSV to JSON in Node.js.

How to Convert Comma-Separated CSV to JSON in Node.js?

This section enlists the step-by-step instructions to convert the comma-separated values to JSON in Node.js.

Step 1: Initialize a Node.js Project

Initialize the Node.js project by executing the below-stated “npm(node package manager)” initialization command:

npm init -y

In the above command, the “-y” flag is used to answer all the queries “yes”.

The output shows that the “package.json” file is successfully created containing the following set of properties:

Folder Structure

The folder structure of Node.js projects looks like this after its initialization:

Step 2: Create “index.js” File

Create a new “.js” file for writing the source code to convert comma-separated CSV to JSON:

Step 3: Install the “CSVtoJSON” Module in Node.js

Install the “CSVtoJSON” module into the Node.js project with the help of the below-stated “npm(node package manager)” installation command:

npm install --save csvtojson

In the above command the “–save” flag adds the install module in the “dependencies” option of the “package.json” file:

The output shows that the “CSVtoJSON” is added to the current node.js project:

Install the “CSVtoJSON” Module Globally

Apart from a specific Node.js project, the user can also install the “CSVtoJSON” module globally in the operating system. For this purpose, execute the installation command along with the “-g” flag in the Windows command prompt:

npm install -g csvtojson

At this time, the “CSVtoJSON” module is added for all Node.js projects into the current operating system:

Step 4: Create a CSV File in the Root Directory

Create a CSV file with the “.csv” extension in the root directory, and add some comma-separated values in it as dummy data:

Step 5: Convert CSV to JSON

Insert the following lines of code into the “index.js” file to convert the CSV data to JSON:

const csvFilePath= "./myCSV.csv"

const csv=require('csvtojson')

csv()

.fromFile(csvFilePath)

.then((jsonObj)=>{

  console.log(jsonObj);

})

The description of the above code lines is written below:

  • First, the “csvFilePath” variable specifies the name and path of the CSV file that needs to be converted to JSON.
  • Next, the “require()” method imports the “csvtojson” module to implement its methods into the Node.js application.
  • After that, invoke an empty function that uses the “.fromFile()” and the “.then()” methods.
  • The “.fromFile()” method accesses CSV file data and the “.then()” method converts it into the JSON array object. Moreover, the “.then()” method also defines a callback function that uses the “console.log()” method to display the converted CSV data to JSON.

Step 6: Execute the Node.js Script File

Execute the above particular “index.js” script file using the below-stated command:

node index.js

The output shows that the specified CSV file content has been converted to JSON successfully. It can be seen that each value written in the first row of the CSV file is taken as a “key” and the subsequent value is its corresponding “value”:

How to Write a Converted Comma-Separated CSV to JSON File?

The user can also write the converted CSV file content into a new file having a “.json” extension. For this purpose, use the “writeFile()” method of the “fs(File System)” module. The “fs.writeFile()” is an asynchronous method that writes data into a file without blocking the remaining program execution.

The following code block shows the practical implementation of writing a converted CSV file content into a new “myJSON.json” file:

const csvFilePath= "./myCSV.csv"

const csv= require('csvtojson')

const fs= require('fs')

csv()

.fromFile(csvFilePath)

.then((jsonObj)=>{

   console.log(jsonObj);

fs.writeFile("myJSON.json",JSON.stringify(jsonObj), (err)=>{

if(err) {

  console.error(err);

}

else{

  console.log("Converted Content has been written to a file successfully!")

  }

})

})

In the above code block:

  • The “require()” method includes the “fs” module in the Node.js application.
  • The “fs.writeFile()” method specifies the file name, stringify() method, and the callback arrow function as its arguments.
  • The file name specifies the file in which the converted content will be written. If the specified file is not present in the given path then the “fs.writeFile()” method creates it automatically.
  • The “JSON.stringify()” method converts the JSON array object to the string format.
  • The “callback” arrow function with an “err” parameter executes after the completion of the defined task.
  • Inside the callback function, the “if-else” statement is utilized. If any error occurs then the “if” statement will execute to display that error via the “console.error()” method. Otherwise, the “else” code block will display the verification message using the “console.log()” method.

Output

Now execute the “index.js” file to see the output:

node index.js

The below output shows a success message after writing the converted content to JSON:

For more verification look at the folder structure of the current Node.js project.

It can be analyzed that the new file named “myJSON.json” has been created successfully in the Node.js project containing the converted CSV file content to JSON:

That’s all about converting comma-separated CSV to JSON in Node.js.

Conclusion

To convert comma-separated CSV to JSON in Node.js, initialize a Node.js project, create a “.js” extension file, and install the “csvtojson” module. After that, create a “.csv” file and convert its content to JSON. Once all is done, execute the “.js” file via the “node <filename.js>” command to display the converted CSV content on the console. In addition, the user can also write the converted content into a “.json” file via the “fs.writeFile()” method. This guide has demonstrated the complete procedure to convert comma-separated CSV to JSON in Node.js.

Share Button

Source: linuxhint.com

Leave a Reply