首页 > 解决方案 > 将 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 函数以将带有子项的项目放到新行上的指针将不胜感激。

标签: javascriptjsoncsv

解决方案


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
            });
        }
    }
});

推荐阅读