我有一个类似的文件:
[
{
"subscriberid": "4355",
"Title": "Miss",
"FirstName": "FirstName",
"LastName": "LastName",
"EmailAddress": "thisisanemail@email.com",
"Mobile": "",
"Postcode": "B1 3qq",
"Gender": "",
"SubscribeDate": "2015-08-12 10:58:29",
"Birthday": "31-5-1985",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "1113111",
"attendreason": "Array",
"MarketingOptIn": "Y",
"Source": "WEBSITE",
"Login": [
{
"subscriberid": "4355",
"Created_at": "2017-05-18 10:09:44",
"IPaddress": "1.1.2.3"
}
]
},
{
"subscriberid": "125",
"Title": "",
"FirstName": "FirstName2",
"LastName": "LastName2",
"EmailAddress": "thisisalsoanemail@email.com",
"Mobile": "",
"Postcode": "tn39 4de",
"Gender": "",
"SubscribeDate": "2015-12-02 17:21:18",
"Birthday": "13-3-1922",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "8108200",
"attendreason": "Date",
"MarketingOptIn": "Y",
"Source": "FACEBOOK",
"Vouchers": [
{
"subscriberid": "213",
"Created_at": "2017-05-18 08:57:47",
"Source": "some website",
"offer": "50offMains",
"name": "50% off Mains"
}
],
"Login": [
{
"subscriberid": "123",
"Created_at": "2017-05-18 07:57:46",
"IPaddress": "1.2.3.4"
}
]
}
]
我正在尝试将其自动转换为CSV格式。通常这将是一个非常简单的json2csv脚本,但由于某种原因,这次我遇到了一个问题,我正在努力解决问题。我的文件正在创建,但只包含标题而没有数据。
我在https://github.com/zemirco/json2csv
上阅读了文档,我想我会在字段中使用点符号,但由于它的设置方式,我不确定点之前会有什么?
我尝试了CLI版本和实际的JS版本但同样的交易。我得到的只是标题。正如您将在脚本中看到的那样,我只关心JSON文档的各个部分,但即使我尝试全部完成,我仍然只能获得标题。我以前的版本都使用了glob,但是直接指向文件的CLI仍会得到相同的结果。
var json2csv = require('json2csv');
var fs = require('fs');
var glob = require('glob');
let fields =
[
"subscriberid",
"Title",
"FirstName",
"LastName",
"EmailAddress",
"Mobile",
"Postcode",
"Gender",
"SubscribeDate",
"Birthday",
"Kids",
"Kidsages",
"Student",
"Favourite",
"attendreason",
"MarketingOptIn",
"Source"
];
let dataInput = glob("path/**/toFile.txt");
var csv = json2csv({ data: dataInput, fields: fields });
fs.writeFile('output.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});