convert csv to json in nojdejs

How to Convert CSV to JSON in NodeJS

NodeJS is a popular javascript based web framework to create JS-based websites and applications. Sometimes you may need to convert CSV to JSON file using NodeJS. In this article, we will look at how to convert CSV file to JSON. We will use csvtojson NodeJS module for this purpose. We will look at two use cases – how to convert csv file to json output, and how to convert csv file to json file.


How to Convert CSV to JSON in NodeJS

Here are the steps to convert csv to json in NodeJS.


1. Create NodeJS app

Open terminal, navigate to the folder where you want to create NodeJS project and run the following command to create a new NodeJS project.

$ npm init -y

This will create a new NodeJS project folder.

Also read : How to Set Upstream Branch in Git


2. Install csvtojson module

Open terminal and run the following commands to install csvtojson module.

$ npm install csvtojson --save

Also read : How to Write to File in Bash


3. Create CSV file

Create a sample CSV file to be converted into JSON.

$ sudo vi sample.csv

Copy paste the following csv data into this file.

id,name,email,country,age
100,John Doe,john@website.com,US,35
101,Jane Doe,jane@website.com,UK,30
102,John Lee,john@website.com,FR,20
103,Greg Hoover,greg@website.com,US,35

Also read : How to Disable HTTP Strict Transport Security Policy in Apache


4. Create app.js to convert CSV to JSON

Run the following command to create a js file app.js that will be used to convert the above CSV file to JSON.

$ sudo vi app.js

Add the following lines to it.

// require csvtojson module
const CSVToJSON = require('csvtojson');

// convert users.csv file to JSON array
CSVToJSON().fromFile('sample.csv')
    .then(users => {
        // users is a JSON array
        // log the JSON array
        console.log(users);
    }).catch(err => {
        // log error if any
        console.log(err);
    });

The above code will load a csv file and convert it into json such as that each value in first row is converted into a key, and each value in subsequent rows are used as corresponding values for these keys.

Also read : How to Increase Request Timeout in NodeJS


5. Run NodeJS app

Run the NodeJS app with following command.

$ sudo node app.js

You will see the following output

[ { id: '100',
    name: 'John Doe',
    email: 'john@website.com',
    country: 'US',
    age: '35' },
  { id: '101',
    name: 'Jane Doe',
    email: 'jane@website.com',
    country: 'UK',
    age: '30' },
  { id: '102',
    name: 'John Lee',
    email: 'john@website.com',
    country: 'FR',
    age: '20' },
  { id: '103',
    name: 'Greg Hoover',
    email: 'greg@website.com',
    country: 'US',
    age: '35' } ]


Write CSV to JSON File

Here is a simple JS code to write JSON object users to file users.json.

fs.writeFile('users.json', JSON.stringify(users, null, 4), (err) => {
    if (err) {
        throw err;
    }
});

If you want to write csv to json file, just update app.js to the following. In this case, we will need to use fs module to write files.

// require csvtojson module
const CSVToJSON = require('csvtojson');
const fs = require('fs');

// convert users.csv file to JSON array
CSVToJSON().fromFile('sample.csv')
    .then(users => {
        // users is a JSON array
        // write JSON array to file
         fs.writeFile('users.json', JSON.stringify(users, null, 4), (err) => {
            if (err) {
               throw err;
             }
          });

    }).catch(err => {
        // log error if any
        console.log(err);
    });

In this article, we have learnt how to convert CSV to JSON using csvtojson module. We have learnt to write output to JSON object as well as JSON file.

Also read : How to Enable CORS in NodeJS


3 thoughts on “How to Convert CSV to JSON in NodeJS

    • You need to store the list of file paths to csv files in an array, loop through it, and in each iteration call CSVToJSON.fromFile() function. Here is an example.

      // require csvtojson module
      const CSVToJSON = require(‘csvtojson’);

      var myArray = [“sample1.csv”,”sample2.csv”];
      var users=[];
      var arrayLength = myArray.length;
      for (var i = 0; i < arrayLength; i++) { CSVToJSON().fromFile(myArray[i]) .then(users[i] => {
      // users is a JSON array
      // log the JSON array
      console.log(users[i]);
      }).catch(err => {
      // log error if any
      console.log(err);
      });
      }

      In the above code, we store each file’s data as separate item in users array.

Leave a Reply

Your email address will not be published. Required fields are marked *