Reputation: 161
I'm receiving a JSON output from an API, and i want to use it with JS and also save that output to file. Is there any way to trigger the browser download machanism using JS with thet output?
Upvotes: 2
Views: 2486
Reputation: 4965
You could try it with a data URI:
function triggerDownload(json) {
var dataUri = 'data:text;charset=utf-8,' + json;
window.open(dataUri);
}
Try entering data:text;charset=utf-8,{"Key":"Value"}
into your browsers address bar. It should show you the save dialog.
See here for more information and browser support.
Upvotes: 0
Reputation: 16706
Maybe now some browsers support the attribute download
but you don't trigger the browser to automatically download the file.
the only way i know is @BAS's solution but without a filename.
tested in chrome ..
array=[{a:'1',b:'2'},{x:'3',y:'4'}];
function dl(array,filename){
var b=document.createElement('a');
b.download=filename;
b.textContent=filename;
b.href='data:application/json;base64,'+
window.btoa(unescape(encodeURIComponent(JSON.stringify(array))))
// or
// b.href='data:application/javascript;charset=utf-8,'+JSON.stringify(json);
return b
}
document.body.appendChild(dl(array,'my.json'));
example
UPDATE direct download works ... on chrome i tested.
on append simulate click
var e=document.createEvent('Events');
e.initEvent('click',true,false);
document.getElementById('dl').dispatchEvent(e);
Upvotes: 3