javascript - 将 json 转换为 csv 但使用 javascript 将子项分成自己的行
问题描述
美好的一天,我正在尝试将 json 数据转换为 csv 文件。目前,当生成 csv 文件时,它不会将带有子项的项目放在自己的行上。
下图显示了数据在 csv 文件中的显示方式。
┌──────────────┬────────────────────────┬────────── ────────┬──────────────┬────────────┐ │ 名称 │ 社交包 │ 产品名称 │ 产品成本 │ 总成本 │ ├──────────────┼────────────────────────┼────────── ────────┼──────────────┼────────────┤ │ 李小龙 │ 无 │ 样题 │ 2500 │ 17100 │ │ │ 无 │ 另一个称号 │ 600 │ │ │ │ 无 │ 又一个称号 │ 14000 │ │ │ 超人 │ 12 周首发 │ 无 │ 0 │ 2215 │ │ 蝙蝠侠 │ 26 周保费 │ 样本标题 │ 4500 │ 6758 │ │ Wonder Woman │ 123 Marketing Starter │ 称号名称 │ 0 │ 4575 │ │ │ 26 启动器 │ 无 │ 2500 │ 8750 │ └──────────────┴────────────────────────┴────────── ──────────┴──────────────┴────────────┘
这是我目前正在使用的数据样本
[
{
"Name": "Bruce Lee",
"SocialPackages": ["None", "None", "None"],
"ProductTitle": ["Sample title", "Another title", "Yet AnotherTitle"],
"ProductCost": [2500, 600, 1400],
"TotalCost": 17100
},
{
"Name": "Bruce Lee",
"Social Packages": ["None"],
"ProductTitle": ["Sample title"],
"ProductCost": [2500],
"TotalCost": 4580
},
{
"Name": "Bruce Lee",
"SocialPackages": ["None", "None", "None"],
"ProductTitle": ["Sample title", "Another title", "Yet AnotherTitle"],
"ProductCost": [2500, 600, 1400],
"TotalCost": 17100
}
]
这是我用来将数据格式化为用户友好版本的功能。
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
function download(){
var headers = {
userName: 'Name',
socialPackages: "Social Packages",
productTitle : "Product Title ",
poroductCost: "Product Cost",
totalCost: "Total Cost"
},
itemsFormatted = [],
fileTitle = 'Export';
// format the data
campaignData.forEach((item) => {
itemsFormatted.push({
userName: item.userName,
socialPackages: item.socialPackages,
productTitle: item.productTitle,
poroductCost: item.poroductCost,
totalCost: item.totalCost
});
});
// call the exportCSVFile() function to process the JSON and trigger the download
exportCSVFile(headers, itemsFormatted, fileTitle);
}
任何有关如何修改 convertToCSV 函数以将带有子项的项目放到新行上的指针将不胜感激。
解决方案
JSON数据有一些问题。在第二个 JSON 对象中,“社交包”中有一个空格。如果已更正,则可以根据需要使用以下代码生成 CSV。
function convertToCSV(objArray) {console.log(objArray)
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
function download(){
var headers = {
userName: 'Name',
socialPackages: "Social Packages",
productTitle : "Product Title ",
poroductCost: "Product Cost",
totalCost: "Total Cost"
},
itemsFormatted = [],
fileTitle = 'Export';
// format the data
campaignData.forEach((item) => {console.log(item)
if (item.SocialPackages.length == 1) {
itemsFormatted.push({
userName: item.Name,
socialPackages: item.SocialPackages,
productTitle: item.ProductTitle,
poroductCost: item.ProductCost,
totalCost: item.TotalCost
});
} else {
for (i = 0; i < item.SocialPackages.length; i++) {
var itemName = ' ';
var itemCost = ' ';
if(i == 0) {
itemName = item.Name;
itemCost = item.TotalCost;
}
itemsFormatted.push({
userName: itemName,
socialPackages: item.SocialPackages[i],
productTitle: item.ProductTitle[i],
poroductCost: item.ProductCost[i],
totalCost: itemCost
});
}
}
});
推荐阅读
- c++ - 尝试包含该头文件时,在头文件中包含特定函数的原因和错误
- arrays - &a[i][j] 如何被评估为 *(a+i)+j
- c++ - 在 LC 简单问题中使用向量不断导致某种 seg fault 错误
- windows - 如何在 sourceforge 获得 mingw-w64?
- node.js - 从 gulp 3.0 迁移到 gulp 4.0
- integer - 在 Odoo 13 中整数字段的计算字段中出现问题
- google-sheets - 使用随机数据在逗号分隔的行中查找重复值
- java - 正确计算插入排序比较的次数
- python - Django中的这个用户参数是什么?
- swift - 发送字典数组 Alamofire + swift