Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 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
  • Example

    code1.js




    // Import csv-writer
    import csvwriter from 'csv-writer'
      
    var createCsvWriter = csvwriter.createObjectCsvWriter
      
    // Passing the column names intp the module
    const 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 array
    const 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 records
    csvWriter
      .writeRecords(results)
      .then(()=> console.log('Data uploaded into csv successfully'));
  • To start the conversion run the below command.
    node code1.js
  • 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:

  1. Import fs and csv-parser modules.
  2. Create objects for these two(fsdata and csvdata).
  3. 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.js




    // Importing csv-parser into csvdata
    import csvdata from 'csv-parser'
      
    // Importing csv-parser into fsdata
    const fsdata = require('fs');
      
    // Reading csv data row wise from geek_data csv file
    fsdata.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
  • 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.

  1. It is used to process the data with in less number of time.
  2. It is similar to array structure.
  3. JSON is Human-readable and writable which is lightweight text based data interchange format
  4. Though it is derived from a subset of JavaScript, yet it is Language independent.
  5. Thus, the code for generating and parsing JSON data can be written in any other programming language.

Syntax:

csvjson_object.toCSV(fileContent);

Approach :

  1. Define the modules in Node.js
  2. Read a file using fs package
  3. Use toCSV method for convert JSON to CSV
  4. 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
  • Example:

    code1.js




    // Import package csvjson
    import csvjson from 'csvjson'
      
    // Import fs package(file system) 
    // for read and write files
    import 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
  • Output:



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!