0

我需要将 json 数据导出到 csv 文件。我将此代码用作参考并根据我的要求进行了修改。但是我无法成功导出嵌套数据。

JSON:(我的 JSON 的结构)

{
"id":"101",
"name":"User1",
"place":{ 
    "city":"City1",
    "state":"State1"
    },
"access":[{"status":"available"}],
"date" : ["2014-03-06"]
}

下面是我的javascript函数。

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 = this.convertToCSV(jsonObject);

  var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

  var blob = new Blob([csv], {
    type: 'text/csv;charset=utf-8;'
  });
  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, exportedFilenmae);
  } else {
    var link = document.createElement("a");
    if (link.download !== undefined) { // feature detection
      // Browsers that support HTML5 download attribute
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", exportedFilenmae);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      console.log(link.href)
      link.click();
      document.body.removeChild(link);
    }
  }
}

var headers = {
  id: "ID".replace(/,/g, ''), // remove commas to avoid errors
  name: "Name",
  place: "Place",
  city: "City",
  state: "State",
  access: "Access",
  date: "Date"
};

itemsNotFormatted = [{
    "id": "101",
    "name": "User1",
    "place": {
      "city": "City1",
      "state": "State1"
    },
    "access": [{
      "status": "available"
    }],
    "date": ["2014-03-06"]
  },
  {
    "id": "102",
    "name": "User2",
    "place": {
      "city": "City2",
      "state": "State2"
    },
    "access": [{
      "status": "unavailable"
    }],
    "date": ["2016-04-06"]
  }
];

var itemsFormatted = [];

// format the data
itemsNotFormatted.forEach((item) => {
  itemsFormatted.push({
    id: item.id.replace(/,/g, ''), // remove commas to avoid errors,
    name: item.name,
    place: item.place,
    city: item.place.city,
    state: item.place.state,
    access: item.access.status,
    date: item.date
  });
});

var fileTitle = 'orders'; // or 'my-unique-title'

exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download

输出: 使用上面的json数据,我需要得到输出: 预期输出

请帮助我实现这一目标。

4

0 回答 0