问题描述
我需要将 json 数据导出到 csv 文件。我使用 this 代码作为参考并根据我的要求进行了修改。但我无法成功导出嵌套数据。
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(/,// 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
请帮助我实现这一目标。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)