To convert CSV file data to JSON in NodeJs we will be using csvjson module package of npm for the conversion.
npm is basically the package manager which provides the JavaScript runtime environment in the Node.js.
Installation:
npm install csvjson --save
After the setup, we can begin with the implementation. Create a new js file or an existing file which you want to use this module.
Add the following code to the file:
Sample Code:
Step 1-
Calling the csvjson module to be used, using Fs module for file related operations.
var csvjson = require('csvjson');
var fs = require('fs');
Step 2-
Setting up the options
var options = {
delimiter : ',' , // optional
quote : '"' // optional
};
Step 3-
Reading the csv file:
var file_data = fs.readFileSync('PATH To FILE', { encoding : 'utf8'});
Step 4-
The actual conversion of the CSV file to JSON:
var result = csvjson.toObject(file_data, options);
The Result-
Converted JSON data from a file:
console.log(result); //Converted json object from csv data
0 Comment(s)