Created
January 3, 2018 08:17
-
-
Save jeffhuangtw/54b6947a37c1f1c7dd6bc720179181d3 to your computer and use it in GitHub Desktop.
Convert json object to csv download link javascript
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
// Sample: download json as excel file (BOM + utf-16le encoding) | |
// reference: | |
// https://gist.github.com/maciejjankowski/2db91642fb9eaa771111f2c0538e4560 | |
// | |
<script> | |
function JSON2CSV(objArray) { | |
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; | |
var str = ''; | |
var line = ''; | |
// header | |
var head = array[0]; | |
for (var index in array[0]) { | |
var value = index + ""; | |
line += '"' + value.replace(/"/g, '""') + '",'; | |
} | |
line = line.slice(0, -1); | |
str += line + '\r\n'; | |
// data | |
for (var i = 0; i < array.length; i++) { | |
var line = ''; | |
for (var index in array[i]) { | |
var value = array[i][index] + ""; | |
line += '"' + value.replace(/"/g, '""') + '",'; | |
} | |
line = line.slice(0, -1); | |
str += line + '\r\n'; | |
} | |
return str; | |
} | |
$(function() { | |
$("#btnDownloadCSV").click(function() { | |
var json = <%- JSON.stringify(eventDatas) %> | |
var csv = JSON2CSV(json); | |
// download link | |
var a = document.createElement("a"); | |
a.style = "display: none"; | |
// Data URI | |
var bom = decodeURIComponent("%EF%BB%BF");// "\uFEFF\n"; | |
var byteArray = []; | |
csv = bom + csv; | |
csvA = new Uint16Array(csv.split('').map( function(k, v){ | |
return k.charCodeAt(0); | |
})); | |
var blob = new Blob([csvA],{type:'text/csv;charset=UTF-16LE;'}); | |
var blobUrl=URL.createObjectURL(blob); | |
a.href = blobUrl; | |
a.download = "report.csv"; | |
document.body.appendChild(a); | |
a.click(); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment