像这样自己做:
'use strict';
var fs = require('fs');
let myObj = {
"rows": [
[
"New , Visitor",
"(not set)",
"(not set)",
"0"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile",
]
]
}
let stringToReplaceComas = '!!!!';
myObj.rows.map((singleRow) => {
singleRow.map((value, index) => {
singleRow[index] = value.replace(/,/g, stringToReplaceComas);
})
})
let csv = `"${myObj.rows.join('"\n"').replace(/,/g, '","')}"`;
csv = csv.replace(new RegExp(`${stringToReplaceComas}`, 'g'), ',');
fs.writeFile('name.csv', csv, 'utf8', function(err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved.');
} else {
console.log('It\'s saved!');
}
});
使用库
例如:https://github.com/mrodrig/json-2-csv、https://github.com/wdavidw/node-csv、https://github.com/wdavidw/node-csv-stringify
以下是使用json-2-csv(https://github.com/mrodrig/json-2-csv)的示例:
'use strict';
const converter = require('json-2-csv');
let myObj = {
"rows": [
{
value1: "New Visitor",
value2: "(not set)",
value3: "(not set)",
value4: "0"
},
{
value1: "New Visitor",
value2: "(not set)",
value3: "(not set)",
value4: "mobile"
},
{
value1: "New Visitor",
value2: "(not set)",
value3: "(not set)",
value4: "mobile"
},
{
value1: "New Visitor",
value2: "(not set)",
value3: "(not set)",
value4: "mobile",
}
]
}
let json2csvCallback = function (err, csv) {
if (err) throw err;
fs.writeFile('name.csv', csv, 'utf8', function(err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved.');
} else {
console.log('It\'s saved!');
}
});
};
converter.json2csv(myObj.rows, json2csvCallback, {
prependHeader: false
});
一个使用csv-stringify的例子(https://github.com/wdavidw/node-csv-stringify)
'use strict';
var stringify = require('csv-stringify');
var fs = require('fs');
let myObj = {
"rows": [
[
"New Visitor",
"(not set)",
"(not set)",
"0"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile"
],
[
"New Visitor",
"(not set)",
"(not set)",
"mobile",
]
]
}
stringify(myObj.rows, function(err, output) {
fs.writeFile('name.csv', output, 'utf8', function(err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved.');
} else {
console.log('It\'s saved!');
}
});
});
[ "Visitor, New", "(not set)", …]
会变成"New"," Visitor","(not set)", …
。不过,我确实喜欢你在父数组上使用单个.join
的方法,并且我已经更新了我的答案,以引用你使用这种技术的方式。 - gfullam