How to parse JSON object to CSV file using json2csv nodejs module

Viewed 68218

I'm currently learning how to parse a JSON object to a CSV file using the json2csv node module. Have never worked with JSON before, so this is all new to me.

My JSON object is formatted like this:

{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}

And the output CSV file is formatted like this:

"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,

How would I be able to get the CSV output to look like this instead?

name, price, color
"Audi",40000,"blue"

I understand I can call fields directly for just regular JSON data, but I don't understand how it would work under a JSON object.

7 Answers
const { Parser } = require('json2csv');

let myCars = {
    "car":
    {
        "name": ["Audi"],
        "price": ["40000"],
        "color": ["blue"]
    }
};

let fields = ["car.name", "car.price", "car.color"];

const parser = new Parser({
    fields,
    unwind: ["car.name", "car.price", "car.color"]
});

const csv = parser.parse(myCars);

console.log('output',csv);

will output to console

enter image description here

I was able to solve this using the parse method and formatting my json data as an array of objects.

const { parse, Parser } = require('json2csv');
const data = [
     {key: value, key2: value2 },
     {key: value3, key2: value4 }
     ];
const fields = ['key', 'key2'];
const csv = parse(data, { fields });

Then do what you need with the csv variable.

I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!

Install

npm i --save jsonexport

Usage

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

jsonexport({
 "car":[
  {
   "name":"Audi",
   "price":"40000",
   "color":"blue"
  }
 ]
}, function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('cars.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('cars.csv saved');
  });
});

https://github.com/kauegimenes/jsonexport

Related