Skip to content
the poor coder

convert json to csv npm

Poor Man
Published
Reading time
2 min read
On this page

How to Convert JSON to CSV using npm#

If you have a JSON file and want to convert it to a CSV file, you can use npm packages to make the process easier. npm, or Node Package Manager, is a tool that allows developers to share and reuse code. Here are some npm packages that can help you with the conversion:

1. json2csv#

json2csv is a versatile npm package that can convert JSON data to CSV format with a lot of customization options. First, install the package:

JavaScript

npm install json2csv
    

Then, use the package to convert your JSON data to CSV format:

JavaScript

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

const jsonData = [
  {
    name: 'John',
    age: 34,
    gender: 'male'
  },
  {
    name: 'Jane',
    age: 27,
    gender: 'female'
  }
];

const fields = ['name', 'age', 'gender'];

try {
  const parser = new Parser({ fields });
  const csvData = parser.parse(jsonData);
  fs.writeFileSync('output.csv', csvData);
} catch (err) {
  console.error(err);
}
    

2. node-json2csv#

node-json2csv is another npm package that can convert JSON data to CSV format. First, install the package:

JavaScript

npm install node-json2csv
    

Then, use the package to convert your JSON data to CSV format:

JavaScript

const json2csv = require('node-json2csv').parse;
const fs = require('fs');

const jsonData = [
  {
    name: 'John',
    age: 34,
    gender: 'male'
  },
  {
    name: 'Jane',
    age: 27,
    gender: 'female'
  }
];

const fields = ['name', 'age', 'gender'];

try {
  const csvData = json2csv(jsonData, { fields });
  fs.writeFileSync('output.csv', csvData);
} catch (err) {
  console.error(err);
}
    

3. csvjson-csv2json#

If you want to convert from CSV to JSON or vice versa, you can use the csvjson-csv2json npm package. First, install the package:

JavaScript

npm install -g csvjson-csv2json
    

Then, use the package to convert your JSON data to CSV format:

JavaScript

csv2json input.csv > output.json
json2csv -i input.json -f name,age,gender
    

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC