Last active
September 24, 2021 18:50
-
-
Save goodevilgenius/6cd921fce7d007c45e17f6b390153cfb to your computer and use it in GitHub Desktop.
[Download JSON] Force browser to download a JavaScript object as a JSON file, using jQuery, or VanillaJS #webdev #browser #javascript
This file contains hidden or 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
/* 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