【问题标题】:How to convert .csv file to json?如何将 .csv 文件转换为 json?
【发布时间】:2019-02-23 07:23:00
【问题描述】:

我需要读取一个 .csv 文件并将 csv 文件转换为 json 格式并将 json 传递给前端

这是读取 csv 文件并转换为 json 的最佳方式

我的代码是:

fs.readFile(req.files.file.path, function(ferr, file) {
        if (ferr) {
            res.json(HttpStatus.NOT_FOUND, { error: ferr });
        }
        if (file) { //here i will get my file
            //here i need to write code for convert the csv file to json
}

【问题讨论】:

标签: node.js


【解决方案1】:

这是读取 .csv 文件并以 json 格式打印的代码。

首先安装CSV模块 为此,请从控制台执行以下命令:

npm install csv

然后创建一个文件,使用如下代码

var csv = require('csv');
// loads the csv module referenced above.

var obj = csv();

// gets the csv module to access the required functionality
function MyCSV(name, number, id) {
    this.FieldOne = name;
    this.FieldTwo = number;
    this.FieldThree = id;
};
​
var MyData = [];

obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) {
    for (var index = 0; index < data.length; index++) {
        MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2]));
    }
    console.log(MyData);
});

var http = require('http');
//Load the http module.
​
var server = http.createServer(function (req, resp) {
    resp.writeHead(200, { 'content-type': 'application/json' });
    resp.end(JSON.stringify(MyData));
});

server.listen(8080);

完成后使用

启动您的应用
Node app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2013-11-10
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多