【问题标题】:Json to csv in Node JsNode Js中的Json到csv
【发布时间】:2018-10-12 13:08:15
【问题描述】:

我有一个 JSON 数据,想将其下载为 csv 文件。如何在节点 js 中实现这一点? NodeJs 是否为此提供了一些预定义的模块?

附:我还想添加一些格式,例如添加 MONTHLY REPORT 等标题,添加行颜色等。

【问题讨论】:

标签: javascript json node.js export-to-csv node-modules


【解决方案1】:

Node.js json2csv 模块可以工作

以下是一些代码示例:

通过 npm 安装

npm install --save json2csv

在你的 node.js 应用中使用它:

const json2csv = require('json2csv').parse;
const fields = ['field1', 'field2', 'field3'];
const opts = { fields };

try {
  const csv = json2csv(myData, opts);
  console.log(csv);
} catch (err) {
  console.error(err);
}

【讨论】:

    【解决方案2】:

    在这种情况下,我们应该如何将某些特定字段分组到 csv 中的一个标题下,如下所示:

          Usernames
    Name1 | Name2 | Name3
    

    【讨论】:

      【解决方案3】:

      我不了解你们,但我喜欢无需大量额外配置即可按预期工作的小包,尝试使用 jsonexport,非常适用于对象、数组、..而且速度很快!

      安装

      npm i --save jsonexport
      

      用法

      const jsonexport = require('jsonexport');
      
      jsonexport({lang: 'Node.js', module: 'jsonexport'}, function(err, csv){
          if (err) return console.error(err);
          console.log(csv);
      });
      

      https://github.com/kauegimenes/jsonexport

      【讨论】:

        猜你喜欢
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-20
        • 2017-04-08
        • 1970-01-01
        • 2018-01-19
        • 1970-01-01
        相关资源
        最近更新 更多