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

imt*_*hvu 5 csv json node.js

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

我的JSON对象的格式如下:

{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}
Run Code Online (Sandbox Code Playgroud)

输出的CSV文件的格式如下:

"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,
Run Code Online (Sandbox Code Playgroud)

我如何才能使CSV输出看起来像这样?

name, price, color
"Audi",40000,"blue"
Run Code Online (Sandbox Code Playgroud)

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

小智 7

您还可以指示 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');
  });
});
Run Code Online (Sandbox Code Playgroud)


Guy*_*ely 5

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 '';
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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');
  });
});
Run Code Online (Sandbox Code Playgroud)

输出文件内容:

"car.name.0","car.price.0","car.color.0"
"Audi","40000","blue"
Run Code Online (Sandbox Code Playgroud)

作为旁注,克隆并使用您自己的版本:

git clone https://github.com/zeMirco/json2csv.git
Run Code Online (Sandbox Code Playgroud)

添加更改...

使用更改的版本:

npm install /local/path/to/repo
Run Code Online (Sandbox Code Playgroud)


jay*_*esh 5

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);
Run Code Online (Sandbox Code Playgroud)

将输出到控制台

在此处输入图片说明