Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save json string to client pc (using HTML5 API)

I read few older thread about the same, but seen the file API changed a lot recently. My requirement is to save a json file (data is locally in indexdDB, but I need a way to back it up). Since I use indexdDB, I only target recent browsers, mainly chrome. So, it it possible to save data (json string) to client computer?

I have seen http://eligrey.com/demos/FileSaver.js/ , but is there a way to do it natively?

Thanks.

like image 457
bsr Avatar asked May 02 '13 02:05

bsr


5 Answers

You can use a Blob and the HTML5 a[download] feature to provide a JSON backup download:

var data = {a:1, b:2, c:3};
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url  = URL.createObjectURL(blob);

var a = document.createElement('a');
a.download    = "backup.json";
a.href        = url;
a.textContent = "Download backup.json";

Here is a jsfiddle example: http://jsfiddle.net/potatosalad/yuM2N/

like image 196
potatosalad Avatar answered Oct 11 '22 00:10

potatosalad


Yes, you can. This assumes that you have the json in text:

var toDownload=new Blob([text],{type:'x-whatever/x-backup'});
var link=window.URL.createObjectURL(toDownload);
window.location=link;

that is untested, but it should work.

like image 30
markasoftware Avatar answered Oct 11 '22 01:10

markasoftware


You can use FileSaver.js.

Sample code:

//include the js file in html.
<script src="FileSaver.min.js"></script>    

// other code ...

//use it here.
var myjson= "{a:3, b:4}";
var blob = new Blob([myjson], {type: "application/json"});

var saveAs = window.saveAs;
saveAs(blob, "my_outfile.json");

Use JSON.stringify to create a string from JSON.

Fiddle: https://jsfiddle.net/9w9ofec4/3/

like image 29
Samuel Bushi Avatar answered Oct 11 '22 00:10

Samuel Bushi


based on potatosalad answer i experimented with an 'self' updating link:
jsfiddle

function saveAsFile(link, content, filename) {
    var blob = new Blob([content], {type: "text/text"});
    var url  = URL.createObjectURL(blob);

    // update link to new 'url'
    link.download    = filename + ".txt";
    link.href        = url;
}

saveAsFile(this, "YourContent", "HelloWorldFile");

the function saveAsFile() needs the calling a element as first argument.
than it updates the href target to the new blob.

like image 39
Stefan Krüger s-light Avatar answered Oct 11 '22 01:10

Stefan Krüger s-light


function saveAsJSON(data, name=Date.now()+'.json') {
  const a = document.createElement('a')
  a.download = name
  a.href = URL.createObjectURL(new Blob([JSON.stringify(data)], {type: 'application/json'}))
  a.click()
}

// https://stackoverflow.com/questions/62371219/chrome-stops-download-files-from-stackoverflow-snippets
saveAsJSON(['orange', 'banana', {name: 'apple'}])
like image 37
井上智文 Avatar answered Oct 11 '22 01:10

井上智文