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

2
  • 1
    Could you give an example of how you would like the CSV file to look, including the header?
    – Rajit
    Jan 5, 2015 at 15:05
  • I add an image to show what I expect as a result
    – farhad
    Jan 5, 2015 at 17:39

3 Answers 3

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

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);
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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.