Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Last active September 25, 2023 18:35
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save yiwenl/8f2b735a2263bc93ee33 to your computer and use it in GitHub Desktop.
Save yiwenl/8f2b735a2263bc93ee33 to your computer and use it in GitHub Desktop.
Javascript using Blob to save json file
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 );
}
@NiceGuyNimni
Copy link

Amazing code!
Helped me a lot.
Do you know how to make it work for non-english characters?
I get gibberish in the file :(

@pramodvkadam
Copy link

Nice

@achmedzhanov
Copy link

It doesn't work witch non latin symbols

@bagermen
Copy link

bagermen commented Jul 28, 2020

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 );
}

@ALABOET
Copy link

ALABOET commented Dec 1, 2022

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