【问题标题】:Convert json file to csv in RestApi express js在Rest Api express js中将json文件转换为csv
【发布时间】:2020-04-29 23:00:54
【问题描述】:

我在文件 entry.routes.js 中的位置有以下命令:/nodejs-express-mysql/app/routes

app.get("/energy/api/ActualvsForecast/:AreaName/:Resolution/date/:Year-:Month-:Day/format=:Type", entry.findFourteen);

我还在 entry.controller.js 文件中的位置编写了以下代码:/nodejs-express-mysql/app/controllers

exports.findFourteen = (req, res) => {


    Entry.findByPars13(req.params.AreaName,req.params.Resolution,req.params.Year,req.params.Month,req.params.Day,req.params.Types, (err, data) => {
        if (err) {
          if (err.kind === "not_found") {
            res.status(404).send({
              message: `Not found Entry with AreaName ${req.params.AreaName}. Five`
            });
          } else {
            res.status(500).send({
              message: "Error retrieving Entry with AreaName " + req.params.AreaName
            });
          }
        } else{
            if(req.params.Type=="csv"){
                 message:"This is csv and the format is: " +req.params.Type
                 res.send(data);
            }
            else if (req.params.Type=="json"){
                 message:"This is json and the format is: " +req.params.Type
                 res.send(data);
           }
          }
      });
    };

我想在 csv 和 json 的 ifs 中编写一些命令,这样如果用户将格式指定为 csv,它就会以 csv 格式返回数据。 json 作为默认值返回,所以如果我认为不应该这样做,内部会发生变化。我怎么能这样做?

【问题讨论】:

    标签: node.js json csv


    【解决方案1】:

    您可以将json2csv 用于参考:https://www.npmjs.com/package/json2csv npm,如下所示:

    json2csv({ data: yourdata, fields: fields }, function(err, csv) {
        res.setHeader('Content-disposition', 'attachment; filename=data.csv');
        res.set('Content-Type', 'text/csv');
        res.status(200).send(csv);
      });
    

    【讨论】:

    • 我需要为此安装任何东西吗?
    • @thriteen chess 是 json2csv 包npm i json2csv --save
    • 我只是将这部分代码添加到 if 中的答案中?
    • @thriteen chess 是的
    • 内部字段:...我要写什么?我写了 data: data 因为这是我的数据,但我不知道应该在文件中放什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多