我有一个嵌套的json,我想用cavascript在csv中转换并下载它。
以下是json的详细信息:
{
"table_1" : [
{
"a": "apple",
"b": "ball"
},
{
"a": "alpha",
"b": "beta"
}
],
"table_2" : [
{
"m" : "mango",
"n" : 1,
"o" : "orange"
},
{
"m" : "melon",
"n" : 2,
"o" : "olive"
},
{
"m" : "mulberry",
"n" : 3,
"o" : "onion"
}
]
}
所需的CSV就是这样的:
现在,请让我知道,我怎么能做到这一点是JS。 我特意在一个csv文件中查找多个表格输出。很快就会出现。
***请注意,
2表的结构不同
1st ong有2列命名a,b
&安培;
第二个3列命名m,n,o
提前致谢!!
答案 0 :(得分:0)
第一级的简单迭代循环和内部的另一个迭代循环,如果内部循环的第一次迭代 - 添加列名称。
答案 1 :(得分:0)
您可以使用npm
模块https://www.npmjs.com/package/json2csv
$ npm install json2csv --save
var json2csv = require('json2csv');
var fields = ['field1', 'field2', 'field3'];
try {
var result = json2csv({ data: myData, fields: fields });
console.log(result);
} catch (err) {
// Errors are thrown for bad options, or if the data is empty and no fields are provided.
// Be sure to provide fields if it is possible that your data array will be empty.
console.error(err);
}
答案 2 :(得分:0)
最后,我这样做了:
<强>码强>
var data = {
"table_1" : [
{
"a": "apple",
"b": "ball"
},
{
"a": "alpha",
"b": "beta"
}
],
"table_2" : [
{
"m" : "mango",
"n" : 1,
"o" : "orange"
},
{
"m" : "melon",
"n" : 2,
"o" : "olive"
},
{
"m" : "mulberry",
"n" : 3,
"o" : "onion"
}
]
};
var csvData = [""];
csvData.push(["+++++++++++++++++++++++"]);
csvData.push(["SAMPLE REPORT"]);
csvData.push(["+++++++++++++++++++++++"]);
csvData.push([""]);
csvData.push(["TABLE 1"]);
csvData.push(["========="]);
csvData.push(["a","b"]);
data.table_1.forEach(function(record){
csvData.push(record);
});
csvData.push(["----------------------------------------------------------"]);
csvData.push([""]);
csvData.push(["TABLE 2"]);
csvData.push(["========="]);
csvData.push(["m","n","o"]);
data.table_2.forEach(function(record){
csvData.push(record);
});
util.JSONToCSVConvertor(util.copy(csvData), "Sample Report", true);
<强>输出:强>
如果有任何其他优化方式,请告诉我。