convert json to csv npm
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:
npm install json2csv
Then, use the package to convert your JSON data to CSV format:
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:
npm install node-json2csv
Then, use the package to convert your JSON data to CSV format:
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:
npm install -g csvjson-csv2json
Then, use the package to convert your JSON data to CSV format:
csv2json input.csv > output.json
json2csv -i input.json -f name,age,gender