如何使用 json2csv nodejs 模块将 JSON 对象解析为 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20620771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON object to CSV file using json2csv nodejs module
提问by imthinhvu
I'm currently learning how to parse a JSON object to a CSV file using the json2csvnode module. Have never worked with JSON before, so this is all new to me.
我目前正在学习如何使用json2csv节点模块将 JSON 对象解析为 CSV 文件。以前从未使用过 JSON,所以这对我来说是全新的。
My JSON object is formatted like this:
我的 JSON 对象格式如下:
{
"car":
{
"name":["Audi"],
"price":["40000"],
"color":["blue"]
}
}
And the output CSV file is formatted like this:
输出 CSV 文件的格式如下:
"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,
How would I be able to get the CSV output to look like this instead?
我如何才能让 CSV 输出看起来像这样?
name, price, color
"Audi",40000,"blue"
I understand I can call fields directly for just regular JSON data, but I don't understand how it would work under a JSON object.
我知道我可以直接为常规 JSON 数据调用字段,但我不明白它在 JSON 对象下如何工作。
采纳答案by Guy Gavriely
json2csv only support a flat structure where fields are direct children of the json root.
json2csv 仅支持平面结构,其中字段是 json 根的直接子级。
if you wish to change it, consider cloning the code and do something like the following:
如果您想更改它,请考虑克隆代码并执行以下操作:
// 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 '';
}
}
usage:
用法:
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');
});
});
output file content:
输出文件内容:
"car.name.0","car.price.0","car.color.0"
"Audi","40000","blue"
as a side note, to clone and work with your own version:
作为旁注,要克隆并使用您自己的版本:
git clone https://github.com/zeMirco/json2csv.git
add changes...
添加更改...
to use changed version:
使用更改的版本:
npm install /local/path/to/repo
回答by Eric Vermeer
You can also direct json2csv to use a sub array within your JSON object by addressing it with .<name>after your JSON object in the data section of json2csv.
您还可以指示 json2csv 在 JSON 对象中使用子数组,方法是在.<name>json2csv 的数据部分中的 JSON 对象之后对其进行寻址。
In your case, this might look something like:
在您的情况下,这可能类似于:
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');
});
});
回答by jayesh
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);
will output to console
将输出到控制台
回答by damphat
The input is bad format, it should like json2csv document:
输入格式错误,它应该像json2csv 文档:
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');
});
});
The content of the "file.csv" should be
“file.csv”的内容应该是
car, price, color
"Audi", 40000, "blue"
"BMW", 35000, "black"
"Porsche", 60000, "green"
回答by Kauê Gimenes
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!
我不知道你们是怎么想的,但我喜欢不需要很多额外配置就可以按预期工作的小包,尝试使用jsonexport,它非常适用于对象、数组等等,而且速度很快!
Install
安装
npm i --save jsonexport
Usage
用法
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');
});
});
回答by user2688473
Check out Underscore.js pluck method- if you pass _.pluck(json, 'car')to json2csv's datainstead of the original json, you should get what you're looking for.
查看Underscore.js pluck方法- 如果你传递_.pluck(json, 'car')给 json2csv'sdata而不是原始的json,你应该得到你正在寻找的东西。


