Convert JSON file into CSV file and displaying the data using Node.js - GeeksforGeeks

09 Apr, 2021
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js.
JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript.
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
Storing data into CSV: There is a csv-writer is a module which is used to store data into CSV.
Syntax :
csv-writer(path,header);
path: File path to download CSV file.
header: Column names in a CSV file just like a dictionary.
Approach:
Import csv-writer after installing it.
Create an object for it.
Mention the values for each column in a constant variable
Use csvWriter.writeRecords(results) for write the data into CSV by csv_writer_object.writeRecords(constant variable)
Follow the below steps to convert a JSON file into a CSV file:
Installing Dependencies:npm install csv-writer
npm install csv-writer
Examplecode1.jscode1.js// Import csv-writerimport csvwriter from 'csv-writer'  var createCsvWriter = csvwriter.createObjectCsvWriter  // Passing the column names intp the moduleconst csvWriter = createCsvWriter({    // Output csv file name is geek_data  path: 'geek_data.csv',  header: [      // Title of the columns (column_names)    {id: 'id', title: 'ID'},    {id: 'name', title: 'NAME'},    {id: 'age', title: 'AGE'},  ]});  // Values for each column through an arrayconst results = [  {    id: '7058',    name: 'Sravan Kumar Gottumukkala',    age: 22  }, {    id: '7004',    name: 'Sudheer',    age: 29  }, {    id: '7059',    name: 'Radha',    age: 45  },{    id: '7060',    name: 'vani',    age: 34  }    ];// Writerecords function to add recordscsvWriter  .writeRecords(results)  .then(()=> console.log('Data uploaded into csv successfully'));
Example
code1.js
// Import csv-writerimport csvwriter from 'csv-writer'  var createCsvWriter = csvwriter.createObjectCsvWriter  // Passing the column names intp the moduleconst csvWriter = createCsvWriter({    // Output csv file name is geek_data  path: 'geek_data.csv',  header: [      // Title of the columns (column_names)    {id: 'id', title: 'ID'},    {id: 'name', title: 'NAME'},    {id: 'age', title: 'AGE'},  ]});  // Values for each column through an arrayconst results = [  {    id: '7058',    name: 'Sravan Kumar Gottumukkala',    age: 22  }, {    id: '7004',    name: 'Sudheer',    age: 29  }, {    id: '7059',    name: 'Radha',    age: 45  },{    id: '7060',    name: 'vani',    age: 34  }    ];// Writerecords function to add recordscsvWriter  .writeRecords(results)  .then(()=> console.log('Data uploaded into csv successfully'));
To start the conversion run the below command.node code1.js
node code1.js
Output:
Output:
Display data in CSV: Sometimes we will have to display the JSON file on the server before converting JSON to CSV file to check the data.
Approach:
Import fs and csv-parser modules.Create objects for these two(fsdata and csvdata).Create a data stream by using method called createReadStream with pipe method by passing csv-parser object.
Import fs and csv-parser modules.
Create objects for these two(fsdata and csvdata).
Create a data stream by using method called createReadStream with pipe method by passing csv-parser object.
Syntax:
fs_object.createReadStream('file_name.csv'),pipe(csv_parser_object())
Example:Code1.jsCode1.js// Importing csv-parser into csvdataimport csvdata from 'csv-parser'  // Importing csv-parser into fsdataconst fsdata = require('fs');  // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv')  .pipe(csvdata())  .on('data', (row) => {      // Display data row by row    console.log(row);  })  .on('end', () => {    console.log('success');  });
Example:
Code1.js
// Importing csv-parser into csvdataimport csvdata from 'csv-parser'  // Importing csv-parser into fsdataconst fsdata = require('fs');  // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv')  .pipe(csvdata())  .on('data', (row) => {      // Display data row by row    console.log(row);  })  .on('end', () => {    console.log('success');  });
To display the JSON data run the below command.node code1.js
node code1.js
Output:
Output:
Convert JSON to CSV: In the first method we pass the JSON data inside of our script but we can also attach the JSON file which was laready created.
It is used to process the data with in less number of time.It is similar to array structure.JSON is Human-readable and writable which is lightweight text based data interchange formatThough it is derived from a subset of JavaScript, yet it is Language independent.Thus, the code for generating and parsing JSON data can be written in any other programming language.
It is used to process the data with in less number of time.
It is similar to array structure.
JSON is Human-readable and writable which is lightweight text based data interchange format
Though it is derived from a subset of JavaScript, yet it is Language independent.
Thus, the code for generating and parsing JSON data can be written in any other programming language.
Syntax:
csvjson_object.toCSV(fileContent);
Approach :
Define the modules in Node.jsRead a file using fs packageUse toCSV method for convert JSON to CSVWrite this data into CSV file using fs package
Define the modules in Node.js
Read a file using fs package
Use toCSV method for convert JSON to CSV
Write this data into CSV file using fs package
Follow the below steps to convert a JSON file into a CSV file:
Installing Dependencies:npm install csvjson fs
Installing Dependencies:
npm install csvjson fs
Example:code1.jscode1.js// Import package csvjsonimport csvjson from 'csvjson'  // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile;  // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => {    if (err) {        // Doing something to handle the error or just throw it        console.log(err);         throw new Error(err);    }      // Convert json to csv function    const csvData = csvjson.toCSV(fileContent, {        headers: 'key'    });      // Write data into csv file named college_data.csv    writeFile('./college_data.csv', csvData, (err) => {        if(err) {            // Do something to handle the error or just throw it            console.log(err);             throw new Error(err);        }        console.log('Data stored into csv file successfully');    });});
Example:
code1.js
// Import package csvjsonimport csvjson from 'csvjson'  // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile;  // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => {    if (err) {        // Doing something to handle the error or just throw it        console.log(err);         throw new Error(err);    }      // Convert json to csv function    const csvData = csvjson.toCSV(fileContent, {        headers: 'key'    });      // Write data into csv file named college_data.csv    writeFile('./college_data.csv', csvData, (err) => {        if(err) {            // Do something to handle the error or just throw it            console.log(err);             throw new Error(err);        }        console.log('Data stored into csv file successfully');    });});
To start the conversion run the below command.node code1.js
node code1.js
Output:
JSON
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?