我有一个返回json对象的url。
我需要有一个按钮与onClick函数,将调用该API,获得json对象,将其转换为CSV,并允许用户下载到他们的本地机器上。
CSV文件应具有如下结构:
"Header 1","Header 2","Header 3","Header 4","Header 5","Header 6","Header 7","Header 8","Header 9","Header 10","Header 11","Header 12"
"B-E7BE5602-2F9B-E3","11608501","Active","2023-06-29","1","0","1","ID","OPEN","Yes","Yes","FLOWER"
"B-480A8929-57D5-97","11608502","Active","2023-06-29","1","0","1","ID","OPEN","No","No","FLOWER"
这是我从API得到的json:
{
"items": {
"recordsFiltered": 2,
"data": [{
"numOfIds": 1,
"productId": null,
"askOrgId": "Yes",
"orderId": 11608501,
"orgSelectionType": "FLOWER",
"batchCode": "B-E7BE5602-2F9B-E3",
"IDType": "OPEN",
"batchId": 413,
"creationDate": "2022-06-29",
"isOnline": "Yes",
"productName": null,
"batchProductArray": [{
"ID": 663255,
"TYPE": "PRODUCT",
"NAME": "SOME NAME"
}
],
"numOfUsedIDs": 0,
"redemptionMethod": "ID",
"askSSN": "No",
"askEmployeeId": "Yes",
"batchStatus": "Active",
"productType": null,
"expirationDate": "2023-06-29"
}, {
"numOfIds": 1,
"productId": null,
"askOrgId": "No",
"orderId": 11608502,
"orgSelectionType": "LEAF",
"batchCode": "B-480A8929-57D5-97",
"IDType": "OPEN",
"batchId": 414,
"creationDate": "2022-06-29",
"isOnline": "Yes",
"productName": null,
"batchProductArray": [{
"ID": 663255,
"TYPE": "PRODUCT",
"NAME": "Other Name"
}
],
"numOfUsedIDs": 0,
"redemptionMethod": "ID",
"askSSN": "No",
"askEmployeeId": "No",
"batchStatus": "Active",
"productType": null,
"expirationDate": "2023-06-29"
},
],
"draw": 1,
"recordsTotal": 2
}
}
我尝试了下面的代码,但它给我,我的json是未定义的
function downloadJSONAsCSV(endpoint) {
// Fetch JSON data from the endpoint
fetch(endpoint)
.then(response => response.json())
.then(jsonData => {
// Convert JSON data to CSV
let csvData = jsonToCsv(jsonData);
// Create a CSV file and allow the user to download it
let blob = new Blob([csvData], { type: 'text/csv' });
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'data.csv';
document.body.appendChild(a);
a.click();
})
.catch(error => console.error(error));
}
function jsonToCsv(jsonData) {
let csv = '';
// Get the headers
let headers = Object.keys(jsonData[0]);
csv += headers.join(',') + '\n';
// Add the data
jsonData.forEach(function(row) {
let data = headers.map(header => row[header]).join(',');
csv += data + '\n';
});
return csv;
}
另外,我相信上面的代码不会将CSV文件格式化为我需要的格式。
1条答案
按热度按时间oprakyz71#
我相信你的代码的问题是你试图把json数据的根节点转换成csv而不是数据的根节点,要解决这个问题,你只需要把
jsonToCsv(jsonData)
改为jsonToCsv(jsonData.items.data)
。另外,你需要为数据Map函数添加一个JSON.stringify
语句。我对你的代码做了必要的修改,并把它们附在下面