json - 如何使用 json2csv nodejs 模块将 JSON 对象解析为 CSV 文件

标签 json node.js csv

我目前正在学习如何使用 json2csv 将 JSON 对象解析为 CSV 文件 Node 模块。以前从未使用过 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 对象下如何工作。

最佳答案

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

关于json - 如何使用 json2csv nodejs 模块将 JSON 对象解析为 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20620771/

相关文章:

node.js - 拒绝(TypeError): Cannot read property 'setState' of undefined,未捕获( promise )TypeError:无法读取未定义的属性 'setState'

excel - cakephp excel/csv 导出组件

java - H2 数据库,使用 Java CSVREAD 合并到表中

python - 将 Counter 编码为 Json 对象

javascript - 检查单元测试中是否调用了函数

javascript - node.js reSTLer 调用的多个响应

javascript - 使用 d3.js 从 csv 文件创建多线图表

javascript - 表单转换为错误的 json 格式

json - 解析 JSON 时遇到问题

java - 根据字段值用 GSON 解析 JSON(与 retrofit 一起使用)