Last active
September 25, 2023 18:35
-
-
Save yiwenl/8f2b735a2263bc93ee33 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 ); | |
} |
Nice
It doesn't work witch non latin symbols
Better to replace encode function with
var encode = function( s ) {
var out = [];
for ( var i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint16Array( out );
}
thank you so much! just wanna point out that now instead of setting up link as a thing with properties you can use = , for example: link.href = url, just saves a bit time.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Amazing code!
Helped me a lot.
Do you know how to make it work for non-english characters?
I get gibberish in the file :(