【问题标题】:How to parse JSON object to CSV file using json2csv nodejs module如何使用 json2csv nodejs 模块将 JSON 对象解析为 CSV 文件
【发布时间】:2014-01-04 10:12:20
【问题描述】:

我目前正在学习如何使用 json2csv 节点模块将 JSON 对象解析为 CSV 文件。以前从未使用过 JSON,所以这对我来说是全新的。

我的 JSON 对象的格式如下:

{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}

输出的 CSV 文件格式如下:

"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,

我怎样才能让 CSV 输出看起来像这样?

name, price, color
"Audi",40000,"blue"

我知道我可以直接为常规 JSON 数据调用字段,但我不明白它在 JSON 对象下是如何工作的。

【问题讨论】:

    标签: json node.js csv


    【解决方案1】:

    json2csv 仅支持字段是 json 根的直接子级的平面结构。

    如果您想更改它,请考虑克隆代码并执行以下操作:

    // createColumnContent function changed from original code
    var createColumnContent = function(params, str, callback) {
      params.data.forEach(function(data_element) {
        //if null or empty object do nothing
        if (data_element && Object.getOwnPropertyNames(data_element).length > 0) {
          var line = '';
          var eol = os.EOL || '\n';
          params.fields.forEach(function(field_element) {
            // here, instead of direct child, getByPath support multiple subnodes levels
            line += getByPath(data_element, field_element.split('.'), 0) + params.del;
          });
          //remove last delimeter
          line = line.substring(0, line.length - 1);
          line = line.replace(/\\"/g, '""');
          str += eol + line;
        }
      });
      callback(str);
    };
    
    var getByPath = function(data_element, path, position) {
      if (data_element.hasOwnProperty(path[position])) {
        if (position === path.length - 1) {
          return JSON.stringify(data_element[path[position]]);
        }
        else {
          return getByPath(data_element[path[position]], path, position + 1)
        }
      }
      else {
        return '';
      }
    }
    

    用法:

    json2csv({data: json, fields: ['car.name.0', 'car.price.0', 'car.color.0']}, function(err, csv) {
      if (err) console.log(err);
      fs.writeFile('file.csv', csv, function(err) {
        if (err) throw err;
        console.log('file saved');
      });
    });
    

    输出文件内容:

    "car.name.0","car.price.0","car.color.0"
    "Audi","40000","blue"
    

    附带说明,克隆并使用您自己的版本:

    git clone https://github.com/zeMirco/json2csv.git
    

    添加更改...

    使用更改的版本:

    npm install /local/path/to/repo
    

    【讨论】:

      【解决方案2】:
      const { Parser } = require('json2csv');
      
      let myCars = {
          "car":
          {
              "name": ["Audi"],
              "price": ["40000"],
              "color": ["blue"]
          }
      };
      
      let fields = ["car.name", "car.price", "car.color"];
      
      const parser = new Parser({
          fields,
          unwind: ["car.name", "car.price", "car.color"]
      });
      
      const csv = parser.parse(myCars);
      
      console.log('output',csv);
      

      将输出到控制台

      【讨论】:

        【解决方案3】:

        您还可以通过在 json2csv 的数据部分中的 JSON 对象之后使用 .<name> 寻址来指示 json2csv 使用 JSON 对象中的子数组。

        在您的情况下,这可能类似于:

        const json2csv = require('json2csv');
        const fs = require('fs');
        
        var json = {
         "car":[
          {
           "name":"Audi",
           "price":"40000",
           "color":"blue"
          }
         ]
        };
        
        json2csv({data: json.car, fields: ['name', 'price', 'color']}, function(err, csv) {
          if (err) console.log(err);
          fs.writeFile('cars.csv', csv, function(err) {
            if (err) throw err;
            console.log('cars file saved');
          });
        });

        【讨论】:

          【解决方案4】:

          输入格式错误,应该是json2csv document:

          var json2csv = require('json2csv');
          
          var json = [
            {
              "car": "Audi",
              "price": 40000,
              "color": "blue"
            }, {
              "car": "BMW",
              "price": 35000,
              "color": "black"
            }, {
              "car": "Porsche",
              "price": 60000,
              "color": "green"
            }
          ];
          
          json2csv({data: json, fields: ['car', 'price', 'color']}, function(err, csv) {
            if (err) console.log(err);
            fs.writeFile('file.csv', csv, function(err) {
              if (err) throw err;
              console.log('file saved');
            });
          });
          

          “file.csv”的内容应该是

          car,       price, color
          "Audi",    40000, "blue"
          "BMW",     35000, "black"
          "Porsche", 60000, "green"
          

          【讨论】:

          • 您好,感谢您的回复!你能告诉我为什么输入格式不正确吗?最终,我要做的是先从 XML 转换为 JSON,然后再从 JSON 转换为 CSV。 XML 到 JSON 的输入/输出将类似于我的原始格式。
          【解决方案5】:

          我能够使用 parse 方法解决这个问题,并将我的 json 数据格式化为对象数组。

          const { parse, Parser } = require('json2csv');
          const data = [
               {key: value, key2: value2 },
               {key: value3, key2: value4 }
               ];
          const fields = ['key', 'key2'];
          const csv = parse(data, { fields });
          

          然后用 csv 变量做你需要的事情。

          【讨论】:

            【解决方案6】:

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

            安装

            npm i --save jsonexport
            

            用法

            const jsonexport = require('jsonexport');
            const fs = require('fs');
            
            jsonexport({
             "car":[
              {
               "name":"Audi",
               "price":"40000",
               "color":"blue"
              }
             ]
            }, function(err, csv) {
              if (err) return console.error(err);
              fs.writeFile('cars.csv', csv, function(err) {
                if (err) return console.error(err);
                console.log('cars.csv saved');
              });
            });
            

            https://github.com/kauegimenes/jsonexport

            【讨论】:

              【解决方案7】:

              查看Underscore.js pluck method - 如果您将_.pluck(json, 'car') 传递给json2csv 的data 而不是原来的json,您应该会得到您想要的。

              【讨论】:

                猜你喜欢
                • 2015-03-03
                • 1970-01-01
                • 2020-10-02
                • 1970-01-01
                • 1970-01-01
                • 2014-05-29
                • 1970-01-01
                • 2019-07-12
                • 1970-01-01
                相关资源
                最近更新 更多