我如何从.csv转换为node.js中的array / json / string

ddy*_*250 1 csv node.js express

我有一个要在node.js / express中使用的csv文件。如何将文件转换为array / json / string类型的变量。我试过了:

fs.readFile('Resource.csv', function(err, data) {
    console.log(data)}
Run Code Online (Sandbox Code Playgroud)

并且尝试了其他我可以在SO中找到的其他东西,但对我没有任何帮助。如果重要的话,数据可以是多行。

L. *_*ros 5

扩展我的评论(来自 csvtojson 文档)

安装 npm i --save csvtojson

然后你像这样使用模块:

CSV 文件:

a,b,c
1,2,3
4,5,6
Run Code Online (Sandbox Code Playgroud)

JS代码:

const csvFilePath='<path to csv file>' // Resource.csv in your case
const csv=require('csvtojson') // Make sure you have this line in order to call functions from this modules
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})
Run Code Online (Sandbox Code Playgroud)

输出 :

[
  {a:"1", b:"2", c:"3"},
  {a:"4", b:"5". c:"6"}
]
Run Code Online (Sandbox Code Playgroud)


Aik*_*wai 5

var fs = require('fs');

var data = fs.readFileSync('Resource.csv')
    .toString() // convert Buffer to string
    .split('\n') // split string to lines
    .map(e => e.trim()) // remove white spaces for each line
    .map(e => e.split(',').map(e => e.trim())); // split each line to array

console.log(data);
console.log(JSON.stringify(data, '', 2)); // as json
Run Code Online (Sandbox Code Playgroud)

  • 如果 csv 的任何字段包含“,”字符,则此解决方案不起作用。 (2认同)