-
-
Save Nas10ka/fec2eee8757db7baf9dc2dda7b66a028 to your computer and use it in GitHub Desktop.
Javascript using Blob to save json file
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
var saveJson = function(obj) { | |
var str = JSON.stringify(obj); | |
var data = encode( str ); | |
var blob = new Blob( [ data ], { | |
type: 'application/octet-stream' | |
}); | |
var url = URL.createObjectURL( blob ); | |
var link = document.createElement( 'a' ); | |
link.setAttribute( 'href', url ); | |
link.setAttribute( 'download', 'data.json' ); | |
var event = document.createEvent( 'MouseEvents' ); | |
event.initMouseEvent( 'click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); | |
link.dispatchEvent( event ); | |
} | |
var encode = function( s ) { | |
var out = []; | |
for ( var i = 0; i < s.length; i++ ) { | |
out[i] = s.charCodeAt(i); | |
} | |
return new Uint8Array( out ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment