JSONToCSV
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
(function(){ | |
var json = JSON.parse(document.getElementsByTagName('pre')[0].innerText); | |
var result = JSON.parse(json.result); | |
document.getElementsByTagName('BODY')[0].appendChild(document.createTextNode("Result to convert: " + JSON.stringify(result, null, 2))); | |
// mock data | |
result = { | |
"result":[ | |
{ | |
"receiver_rank":1, | |
"num_of_units":4, | |
"lcp_receiver":"lcp/glm_0/lcp_chain/domain221_icnips/fall", | |
"driver_rank":1, | |
"min_depth":53.77552798, | |
"units":"n8526s04a00299;n8526s05a00706;mc523217a000867;mc523217a00971", | |
"lcp_driver":"lcp/glm_0/lcp_chain/domain263_dcaddr/rise", | |
"slowest_test":"sl21_lea_x_r6glm_5" | |
}]} ; | |
convertToCSV(result.result,'result', true); | |
function convertToCSV(jsonData, title, includeHeader) { | |
var arrData = typeof jsonData != 'object' ? JSON.parse(jsonData) : jsonData; | |
var CSV = ""; | |
//This condition will generate the Label/Header | |
if (includeHeader) { | |
CSV += Object.keys(arrData[0]).map(function(k){ return '"' + k.split('"').join('""') + '"'}).join(',') + '\r\n'; | |
} | |
var rows = arrData.map(function(row){ | |
return Object.keys(row).map(function(k){ return row[k].toString().indexOf('"') > 0 ? '"' + row[k].split('"').join('""') + '"' : row[k]}) | |
.join(','); | |
}).join('\r\n'); | |
CSV += rows + '\r\n'; | |
var fileName = title.replace(/ /g,"_"); | |
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(CSV); | |
//this trick will generate a temp <a /> tag | |
var link = document.createElement("a"); | |
link.href = uri; | |
//set the visibility hidden so it will not effect on your web-layout | |
link.style = "visibility:hidden"; | |
link.download = fileName + ".csv"; | |
//this part will append the anchor tag and remove it after automatic click | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment