如何解决如何在javascript中将嵌套的json对象导出到csv?
我需要将 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 举报,一经查实,本站将立刻删除。