我正在编写一个函数,该函数应将通用的深层嵌套JSON对象级别转换为JS或TypeScript中的CSV文件.
我尝试了几个库,但是以某种方式它们无法以我希望它正确释放嵌套JSON的方式工作.该代码应展开此输入:
{
[
{
app: "app1",device: [
"c1","c2","c3","c4"
]
},{
app: "app2",device: [
"b1","b2"
]
}
]
}
进入预期结果:
app;device
app1;c1
app1;c2
app1;c3
app1;c4
app2;b1
app2;b2
现在,我正在使用此代码,但结果与预期的不同:
private ConvertToCSV(json: string,fields: string[]): string {
const Json2csvParser = require("json2csv").Parser;
let options: {};
options = { fields };
const parser = new Json2csvParser(options);
const csv = parser.parse(JSON.parse(json));
console.log(JSON.parse(json));
console.log(csv);
return csv;
}
我的结果现在看起来像这样:
"app","device"
"app1","[""c1"",""c2"",""c3"",""c4""]"
"app2","[""b1"",""b2""]"
最佳答案
是的,您可以执行此操作-在文档中带有unwind function的文档中是正确的,尽管您可能需要添加一个转换器以完全按照所需的格式进行格式化.看一看:
原文链接:https://www.f2er.com/js/531183.htmlconst data: any = [
{
app: "app1","b2"
]
}
];
function ConvertToCSV(json: string,fields: any): string {
const Json2csvParser = require("json2csv").parse;
let options: {};
options = fields;
const csv = Json2csvParser(JSON.parse(json),options);
console.log(JSON.parse(json));
console.log(csv);
return csv;
}
ConvertToCSV(JSON.stringify(data),{fields: ['app','device'],unwind: 'device'});