Skip to content

Instantly share code, notes, and snippets.

@c4software
Created September 8, 2020 07:13
Show Gist options
  • Save c4software/79e513f5696b45081ade7a27c38a4ae0 to your computer and use it in GitHub Desktop.
Save c4software/79e513f5696b45081ade7a27c38a4ae0 to your computer and use it in GitHub Desktop.
Produce & Download a JSON object directly from the browser
const saveAsJsonLocally = (obj, filename) => {
const data = JSON.stringify(obj, null, 2);
const blob = new Blob([data], {type: 'text/plain'});
const e = document.createEvent('MouseEvents');
const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false);
a.dispatchEvent(e);
}
out = {id: 'YOLO'};
saveAsJsonLocally(out, 'this-is-a-sample-file.json');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment