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
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