How to convert CSV to JSON in Node.js

CSV (Comma-Separated Values) is a popular data exchange format that stores data in a tabular format where each row consists of one or more fields and each column represents a specific field. Due to simplicity and better integration with existing applications, CSV is widely used for exporting and importing large data sets.

In this article, you'll learn how to parse and convert a CSV file into a JSON array in a Node.js application. We'll write a Node.js script that takes a CSV file as input and outputs its contents as a JSON array.

In order to do the CSV to JSON conversion, we'll be using the csvtojson package from NPM. This package is a Node.js CSV parser to convert CSV to JSON or column arrays.

Create an Application

Let us first create a new Node.js application and install all the required dependencies. Navigate to the folder where you want to store your project and execute the following command in the terminal:

$ npm init -y

This will initialize a new Node.js project and create a package.json file in the root directory. Next, install the csvtojson module by typing the following command:

$ npm install csvtojson --save

The above command will create a node_modules directory inside your project containing all the dependencies that csvtojson requires.

Finally, create a sample CSV file called users.csv with the following content in the root directory:

users.csv

id,name,email,country,age
100,Atta Shah,atta@example.com,PK,30
101,Alex Jones,alex@example.com,DE,35
102,Jovan Lee,jovan@example.com,FR,25
103,Greg Hover,greg@example.com,US,45

Convert CSV to JSON

To convert the above CSV file to JSON, create a new JavaScript file named app.js in the root directory:

$ touch app.js

If the touch command is unavailable, simply create the file manually. Open the app.js file in your favorite editor and add the following code:

app.js

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

// convert users.csv file to JSON array
CSVToJSON()
  .fromFile('users.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 is a complete example that loads a CSV file asynchronously and converts it into a JSON array. The fromFile() method takes in the path to the CSV file and returns a new promise. Once the promise is resolved successfully, the then() method is called with the JSON array as an argument. If csvtojson fails to convert the CSV file to JSON, it will throw an error that will be caught by the catch() method.

To see the output, type the following command in your terminal:

$ node app.js

Here is what the output looks like:

[ { id: '100',
    name: 'Atta Shah',
    email: 'atta@example.com',
    country: 'PK',
    age: '30' },
  { id: '101',
    name: 'Alex Jones',
    email: 'alex@example.com',
    country: 'DE',
    age: '35' },
  { id: '102',
    name: 'Jovan Lee',
    email: 'jovan@example.com',
    country: 'FR',
    age: '25' },
  { id: '103',
    name: 'Greg Hover',
    email: 'greg@example.com',
    country: 'US',
    age: '45' } ]

Write JSON to File

Sometimes you may want to store the newly created JSON array in a file for further processing. Here is an example that demonstrates how to write the JSON array to a file:

// Write JSON array to a file
fs.writeFile('users.json', JSON.stringify(users, null, 4), err => {
  if (err) {
    throw err
  }
  console.log('JSON array is saved.')
})

Read this guide to learn more about writing JSON to a file in a Node.js application.

Async-Await

The csvtojson module also supports the async-await syntax. Let us create a new file called app-async.js with the following content:

app-async.js

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

// convert users.csv file to JSON array
;(async () => {
  try {
    const users = await CSVToJSON().fromFile('users.csv')

    // log the JSON array
    console.log(users)
  } catch (err) {
    console.log(err)
  }
})()

Source Code: Download the complete source code from GitHub available under MIT license.

Conclusion

That's all for converting a Comma-Separated Values (CSV) file into a JSON array in a Node.js application using the csvtojson package. We also discussed writing the JSON array to a file for further processing.

The csvtojson package is a lightweight yet powerful library to convert CSV to JSON in Node.js and browsers. You can even use it as a command-line tool to quickly convert a CSV file to a JSON file.

Read Next: How to convert JSON to CSV in Node.js

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.