【发布时间】:2015-03-03 03:28:42
【问题描述】:
我新学习了 node.js,我想使用 json2csv 节点模块将 JSON 对象解析为 CSV 文件。 json2csv 仅支持平面结构,其中字段是 json 根的直接子级。我找到了how-to-parse-json-object-to-csv-file-using-json2csv-nodejs-module 主题并将json2csv 的createColumnContent 函数更改为读取我的json 文件的对象元素。 但我的 json 文件有数组元素,是这样的:
[
{
"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"
}
]
}
]
我想要这样的东西
我这样调用 json2csv:
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');
});
}
);
如何读取数组并添加到我的 csv 文件。 谢谢
【问题讨论】:
-
您能否举例说明您希望 CSV 文件的外观,包括标题?
-
我添加了一张图片来显示我期望的结果
标签: javascript json node.js csv