Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Download JSON] Force browser to download a JavaScript object as a JSON file, using jQuery, or VanillaJS #webdev #browser #javascript
/* global $, data */
// data should be the object/array/etc to be JSON-ified.
// First, with jQuery
var $el = $('<a>');
$(document.body).append($el);
// If data is a jQuery selector, then do data = data.toArray()
var data_string = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
$el.attr('href', data_string);
$el.attr('download', 'data.json');
$el.get(0).click();
// Second, VanillaJS
var el = document.createElement('a');
document.body.appendChild(el);
var data_string = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
el.setAttribute('href', data_string);
el.setAttribute('download', 'data.json');
el.click();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment