I have a function in my code that fetches JSON data from an endpoint and converts it into a CSV file. Is there a way for me to specify specific headers and the order of columns I want in this CSV file?
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.items.data); // Add .items.data
// 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 => JSON.stringify(row[header])).join(','); // Add JSON.stringify statement
csv += data + '\n';
});
return csv;
}
Desired CSV format:
"Batch Code","Order Id","Batch Status","Batch Expiration Date","Total","Used","Remaining","Redemption Method","Type","Organization Group","Employee ID","Selection Type"
"B-E7BE5602-2F9B-E3","11608501","Active","2023-06-29","1","0","1","ID CARD","OPEN","Yes","Yes","FLOWER"
"B-480A8929-57D5-97","11608502","Active","2023-06-29","1","0","1","ID CARD","OPEN","No","No","FLOWER"
JSON input that needs to be converted into CSV:
{
"numOfItems": {
"records": 2,
"data": [{
"numOfIDs": 1,
"productId": null,
"askOrgId": "Yes",
"orderId": 11608501,
"orgSelectionType": "FLOWER",
"batchCode": "B-E7BE5602-2F9B-E3",
"Type": "OPEN",
"batchId": 413,
"creationDate": "2022-06-29",
"isOnline": "Yes",
"productName": null,
"batchProductArray": [{
"ID": 663255,
"TYPE": "PRODUCT",
"NAME": "SomeName"
}
],
"numOfUsedPassports": 0,
"redemptionMethod": "ID Card",
"askSSN": "No",
"askEmployeeId": "Yes",
"batchStatus": "Active",
"productType": null,
"expirationDate": "2023-06-29"
}
],
"draw": 1,
"recordsTotal": 2
}
}
I attempted to map this JSON data into a specific format but was unsuccessful with that.