[英]How to convert JSON array to CSV using Node.js?
我想轉換具有值數組的 json 。 響應.json
{
"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",
]
]
}
現在我想把這些數據轉換成。 名稱.csv
"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"
請給我使用 Node.js 的建議。
'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",
]
]
}
// 1. One way - if you want the results to be in double quotes and you have comas inside
// choose another string to temporally replace commas if necessary
let stringToReplaceComas = '!!!!';
myObj.rows.map((singleRow) => {
singleRow.map((value, index) => {
singleRow[index] = value.replace(/,/g, stringToReplaceComas);
})
})
let csv = `"${myObj.rows.join('"\n"').replace(/,/g, '","')}"`;
// // or like this
// let csv = `"${myObj.rows.join('"\n"').split(',').join('","')}"`;
csv = csv.replace(new RegExp(`${stringToReplaceComas}`, 'g'), ',');
// // 2. Another way - if you don't need the double quotes in the generated csv and you don't have comas in rows' values
// let csv = myObj.rows.join('\n')
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 // removes the generated header of "value1,value2,value3,value4" (in case you don't want it)
});
使用 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!');
}
});
});
第一步:閱讀。
如果您需要從文件中讀取 JSON(如您在帖子中包含的文件名response.json
),您將需要Node.js FileSystem API :
const fs = require('fs'); // Require Node.js FileSystem API.
const JSONFile = fs.readFileSync('response.json'); // Read the file synchronously.
注意:如果您願意,可以使用fs.readFile()
異步讀取文件並在回調函數中執行轉換。
第 2 步:轉換。
無論您是從本地文件讀取 JSON 還是從服務器獲取它,您都需要首先使用JSON.parse
方法將其解析為普通的舊 JavaScript 對象:
const JSONasPOJO = JSON.parse(JSONFile); // Parse JSON into POJO.
然后對子數組和父數組執行一系列連接:
請參閱下面的編輯
/* THIS IS UNNECESSARY FOR "COMMA" SEPARATED VALUES
const CSVString = JSONasPOJO
.rows // Get `rows`, which is an array.
.map( // Map returns a new array.
row => row.join(',') // Each child array becomes a comma-separated string.
)
.join('\n'); // Parent array becomes a newline-separated string...
// ...of comma-separated strings.
// It is now a single CSV string!
*/
編輯:
雖然前面的代碼肯定有效,但沒有必要在子數組上使用.map
和.join
。 正如@Relu 演示的那樣,父數組上的單個.join
就足夠了,因為 JavaScript 會默認自動將子數組轉換為逗號分隔的字符串,因為.join
必須返回一個字符串並且不能包含任何子數組。
如果你想用逗號以外的東西連接子數組,你可以使用上面的模式。
否則:
var CSVString = JSONasPOJO.rows.join('\n'); // Array becomes a newline-separated...
// ...string of comma-separated strings.
// It is now a single CSV string!
在這里,我們可以看到這種轉換在起作用:
const JSONasPOJO = { "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" // NOTE: Here I removed a trailing comma, // ...which is invalid JSON! ] ] } const CSVString = JSONasPOJO.rows.join('\\n'); console.log(CSVString);
第三步:寫。
再次使用 FileSystem API,寫入文件,並記錄錯誤或成功消息:
fs.writeFile('name.csv', CSVString, err => {
if (err) return console.log(err);
console.log('FILE SUCCESSFULLY WRITTEN!\n');
});
注意:在這里,我演示了使用回調記錄我的錯誤和成功消息的異步模式。 如果您願意,可以使用fs.writeFileSync()
同步寫入文件。
我喜歡在我的 Node.js 腳本中添加大量的console.log()
消息。
const fs = require('fs');
const inFilename = 'response.json',
outFilename = 'name.csv';
console.log(`Preparing to read from ${inFilename} …`);
const JSONContents = fs.readFileSync(inFilename);
console.log(`READ:\n${JSONContents}`);
console.log('Preparing to parse as JSON …');
const JSONasPOJO = JSON.parse(JSONContents);
console.log(`PARSED:\n${JSONasPOJO}`);
console.log('Preparing to convert into CSV …');
const CSVString = JSONasPOJO.rows.join('\n');
console.log(`CONVERTED:\n${CSVString}`);
console.log(`Preparing to write to ${outFilename} …`);
fs.writeFile(outFilename, CSVString, err => {
if (err) return console.error(err);
console.log('FILE SUCCESSFULLY WRITTEN!');
});
在嘗試使用該庫幾個小時后,我最終編寫了自己的庫。 https://github.com/KhanhPham2411/simple-node-csv
import { SimpleNodeCsv } from './simple-node-csv';
SimpleNodeCsv.obj2csv({a: 1, b:2}, ",");
// output
// "a","b"
// 1,2
我不了解你們,但我喜歡無需大量額外配置即可按預期工作的小包,嘗試使用 jsonexport,我認為它是最好的模塊,適用於對象、數組等。它的快!
安裝
npm i --save jsonexport
用法
const jsonexport = require('jsonexport');
const fs = require('fs');
jsonexport([{
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",
}], function(err, csv) {
if (err) return console.error(err);
fs.writeFile('output.csv', csv, function(err) {
if (err) return console.error(err);
console.log('output.csv saved');
});
});
我想分享從 json 數組構建 csv 字符串的最簡單方法:
const data = [ { a: 1, b: new Date(), c: 'a text' }, { a: 1, b: new Date(), c: `string with return carrier and emoji 😂 ` } ] const header = Object.keys(data[0]).map(_ => JSON.stringify(_)).join(';') + '\\n' const outData = data.reduce((acc, row) => { return acc + Object.values(row).map(_ => JSON.stringify(_)).join(';') + '\\n' }, header) console.log(outData)
將打印此字符串:
"a";"b";"c"
1;"2020-03-25T08:49:04.280Z";"a text"
1;"2020-03-25T08:49:04.280Z";"string\n with\n return\n carrier\n and emoji 😂\n "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.