json2csv仅支持平面结构,其中字段是json根的直接子级。
如果您想更改它,请考虑克隆代码并执行以下操作:
// createColumnContent function changed from original prevar 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



