CSV to JSON in Node.js – JSON to CSV example

Introduction

When working with various data sets in Node.js, it’s common to encounter the need to convert data from CSV to JSON format and vice versa. JSON (JavaScript Object Notation) is widely used for its simplicity and ease of use within JavaScript environments, whereas CSV (Comma-Separated Values) is often used for spreadsheets and databases. This tutorial will guide you through how to seamlessly convert CSV to JSON and JSON to CSV in Node.js, complete with code examples and outputs.

Prerequisites

Before diving into the code examples, you should have Node.js installed on your system. You’ll also need the ‘csvtojson’ and ‘json2csv’ libraries, which can be installed using npm:

npm install csvtojson json2csv --save

Converting CSV to JSON

To convert a CSV file to JSON in Node.js, follow this example using the ‘csvtojson’ library:

const csvtojson = require('csvtojson');
const fs = require('fs');

const csvFilePath = 'yourfile.csv';

csvtojson()
  .fromFile(csvFilePath)
  .then((jsonObj) => {
    console.log(jsonObj);
  });

// Output:
// [{"column1":"value1","column2":"value2"}, ... ]

This code snippet reads a CSV file and converts it to JSON. Each row in the CSV file becomes a JavaScript object, with column headers as keys.

Converting JSON to CSV

Similarly, to convert JSON data to a CSV file in Node.js, we can use the ‘json2csv’ library:

const { Parser } = require('json2csv');
const fs = require('fs');

const jsonData = [
  {
    "column1": "value1",
    "column2": "value2"
  }
  // ... more items
];
const json2csvParser = new Parser();
const csv = json2csvParser.parse(jsonData);

console.log(csv);

// Output:
// column1,column2
// value1,value2
// ... more rows

In this code, we used the ‘json2csv’ parser to convert an array of JSON objects into a CSV string. The keys of the first object in the array define the column headers of the CSV.

Conclusive Summary

In conclusion, converting CSV to JSON and JSON to CSV in Node.js is straightforward with the use of ‘csvtojson’ and ‘json2csv’ libraries. The examples provided in this post illustrate how you can perform these conversions efficiently, whether dealing with files or JSON objects in your application. These code snippets will serve as a solid foundation for managing data transformations in your Node.js projects.