Skip to content

Instantly share code, notes, and snippets.

Last active September 24, 2021 18:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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>');
// 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');
// Second, VanillaJS
var el = document.createElement('a');
var data_string = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
el.setAttribute('href', data_string);
el.setAttribute('download', 'data.json');;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment