Created
August 13, 2021 21:40
-
-
Save NickersF/43cf44bae45f90af56320b5d3db6831b to your computer and use it in GitHub Desktop.
JSON To CSV Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Convert JSON to CSV file and automatically download when called | |
function convertJSONtoCSV(JSONData, providedFileName, parseHeaders) { | |
// If JSONData is not an object then JSON.parse will parse the JSON string in an Object | |
let arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; | |
let processedCSV: string = ""; | |
// Generate the headers if argument is passed as true | |
if (parseHeaders) { | |
let row: string = ""; | |
// Extract first value of the a JSON array and comma separate | |
for (let value in arrData[0]) { | |
row += value + ','; | |
} | |
row = row.slice(0, -1); | |
// Insert a row and newline | |
processedCSV += row + '\r\n'; | |
} | |
// Rowise iteration of JSON | |
for (let i = 0; i < arrData.length; i++) { | |
let row = ""; | |
// Columnwise iteration of JSON | |
for (let j in arrData[i]) { | |
row += '"' + arrData[i][j] + '",'; | |
} | |
row.slice(0, row.length - 1); | |
processedCSV += row + '\r\n'; | |
} | |
if (processedCSV == "") { | |
console.log("Invalid data provided. Check API calls and controllers.") | |
return; | |
} | |
// Automatic download feature | |
// Setup the pseudo anchor tag | |
let tempLink = document.createElement("a"); | |
tempLink.id = "downloadCSVLink"; | |
$(document.body).append(tempLink); | |
// Prepare CSV file in browser | |
let csv = processedCSV; | |
let blob = new Blob([csv], { type: 'text/csv' }); | |
let fileUrl = window.webkitURL.createObjectURL(blob); | |
let fileName = (providedFileName || 'County Road Mileage Data') + '.csv'; | |
// Complete download | |
$("#downloadCSVLink") | |
.attr({ | |
'download': fileName, | |
'href': fileUrl | |
}); | |
$("#downloadCSVLink")[0].click(); // Automatic click event | |
$("#downloadCSVLink").remove(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment