json to csv download in the browser

Written in


While using a javascript based datagrid that was displaying json data provided to a page, I thought it smart to not have to re-download all the data again just to make export a csv file.

My solution was to use the “Papa Parse” library to create the CSV file and use URL.createObjectURL() to actually make local data appear as a file which can be downloaded.

I also tried directly setting base64 encoded data to the window like this solution but it choked on my 6-10MB report results.

jQuery(document).ready(function() {
 //My json formatted data from php.
 var dataSet = <?=json_encode($data)?>;
 //select our link, create an objectURL Blob of CSV data.
 jQuery('#downloadCsv').attr('href',URL.createObjectURL(new Blob([Papa.unparse(dataSet)], { type:"text/csv" } ) ) );

and the html for the link:

<a id="downloadCsv" class="button button-secondary" download="reportdata.csv">Download CSV</a>


Verified by MonsterInsights