将Json与CSV文件标题进行比较并填充



Hi有下面的JSON,我想将其与CSV文件中的一组字段名进行匹配并填充。我正在从一个api中获取json数据,并希望在node.js 中动态创建设置的CSV文件

CSV集字段名称:

"Name", "ID", "PRODUCT 1", "PRODUCT 2", "PRODUCT 3"

JSON(为了简单起见,手动示例,如果结构有错误,请道歉(:

[{
name: 'Bob',
id: '100',
products: {[
{item: 'product 1',
qty: '3'},
{item: 'product 2',
qty: '2'}]
},{
name: 'James',
id: '200',
products: {[
{item: 'product 3',
qty: '1'}]
}

所需CSV填充:

CSV字段:

"Name", "ID", "PRODUCT 1", "PRODUCT 2", "PRODUCT 3"
Bob     100    3              2
James   200                                1

我将对CSV列进行整形和展开,然后使用json2csv和fs进行解析和输出。

const { parse } = require('json2csv');
const fs = require('fs');
const items = [
{
name: 'Bob',
id: '100',
products: [
{
item: 'product 1',
qty: '3'
},
{
item: 'product 2',
qty: '2'
}]
}, {
name: 'James',
id: '200',
products: [
{
item: 'product 3',
qty: '1'
}]
}
];
// flatten the needed CSV columns
const flatten = items.map(item => {
const i = {
name: item.name,
id: item.id
};
// pull out products
item.products.forEach(product => {
i[product.item] = product.qty;
});
return i;
});
// Declare the expected fields here
const fields = ['name', 'id', 'product 1', 'product 2', 'product 3'];
const csv = parse(flatten, { fields });
fs.writeFile('items.csv', csv, (err) => {
if (err) throw err;
console.log('CSV file saved');
});

希望我帮过忙。

最新更新