0

How to create a CSV file in JavaScript

 $("#download_1").click(function() {
     var json_pre = '[{"Id":"Header A1","UserName":"Header B1"},{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
     var json = $.parseJSON(json_pre);

     var csv = JSON2CSV(json);
     var downloadLink = document.createElement("a");
     var blob = new Blob(["\ufeff", csv]);
     var url = URL.createObjectURL(blob);
     downloadLink.href = url;
     downloadLink.download = "data.csv";

     document.body.appendChild(downloadLink);
     downloadLink.click();
     document.body.removeChild(downloadLink);
 });

 function JSON2CSV(objArray) {
     var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
     var str = '';
     var line = '';

     if ($("#labels").is(':checked')) {
         var head = array[0];
         if ($("#quote").is(':checked')) {
             for (var index in array[0]) {
                 var value = index + "";
                 line += '"' + value.replace(/"/g, '""') + '",';
             }
         } else {
             for (var index in array[0]) {
                 line += index + ',';
             }
         }

         line = line.slice(0, -1);
         str += line + '\r\n';
     }

     for (var i = 0; i < array.length; i++) {
         var line = '';

         if ($("#quote").is(':checked')) {
             for (var index in array[i]) {
                 var value = array[i][index] + "";
                 line += '"' + value.replace(/"/g, '""') + '",';
             }
         } else {
             for (var index in array[i]) {
                 line += array[i][index] + ',';
             }
         }

         line = line.slice(0, -1);
         str += line + '\r\n';
     }
     return str;
 }
<a href="#" id="download_1">Download CSV</a>
RUN
add comment
Suggest a different solution or add another example