2

I newly learned node.js and I want to parse a JSON object to a CSV file using the json2csv node module. json2csv only support a flat structure where fields are direct children of the json root. I found how-to-parse-json-object-to-csv-file-using-json2csv-nodejs-module topic and changed createColumnContent function of json2csv to read object elemet of my json file. but my json file has array element and is something like this:

[
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
},
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

]

and I want something like that enter image description here

I call json2csv like this:

json2csv({
        data: body.issues, 
        fields: ['firstName','lastname','age','address.city', 'phoneNumber[?].type', 'phoneNumber[?].number']
    }, 
    function(err, csv) {
        if (err) console.log(err);
        fs.writeFile('sample.csv', csv, function(err) {
            if (err) throw err;
            console.log('file saved');
        });  
    }
);

How can I read array and add to my csv file. thank you

Community
  • 1
  • 1
farhad
  • 373
  • 2
  • 14
  • 28

3 Answers3

6

I just released a module that makes this process easy in Node.js

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

Output:

lastname;name;family.type;family.name;nickname;location
Smith;Bob;Father;Peter;;
David;James;Mother;Julie;;
Miller;Robert;;;;1231,3214,4214
Martin;David;;;dmartin;

https://www.npmjs.com/package/jsonexport

Kauê Gimenes
  • 1,278
  • 1
  • 13
  • 30
2

You are probably better off transforming the data yourself than overriding part of the json2csv package. Then you can pass the flat data structure to json2csv for formatting.

    var xform = [];
    for (var i=0, max=data.issuelinks.length; i<max; i++ ) {
            xform[xform.length] = { id:data.id, progress:data.progress.percent, issuelinkid:data.issuelinks[i].id, issuelinktypeid:data.issuelinks[i].type.id } 
    } 
    console.log(xform);
Landon B
  • 61
  • 4
1

As of json2csv v5+, you can do this using flatten and unwind provided with the modules itself.

you can use it like this-

const {
  Parser,
  transforms: { flatten, unwind }
} = require("json2csv");

try {
  const parser = new Parser({
    fields: ["firstColumn", "b.secondColumn", "cars.0.brand", "cars.1.brand"],
    transforms: [flatten({ arrays: true }), unwind({ paths: ["cars"] })]
  });
  const csv = parser.parse({
    firstColumn: "first data",
    b: {
      secondColumn: "second data"
    },
    cars: [{ brand: "AUDI" }, { brand: "TOYOTA" }]
  });
  console.log(csv);
//   OUTPUT:
//  "firstColumn","b.secondColumn","cars.0.brand","cars.1.brand"
//  "first data","second data","AUDI","TOYOTA"
} catch (err) {
  console.log(err);
}
KANE
  • 63
  • 1
  • 1
  • 11