Home > Software design >  Angular Download JSON as separate files and Zipped
Angular Download JSON as separate files and Zipped

Time:07-11

I have been doing some research but unable to get it working

I have an array of JSON which I can call via subscribe method (which is calling REST API)

this.restapi.getData()
      .subscribe(
        results => {
        for (let each of results) {
        ...
        }
      });

each gets multiple results of JSON array..

What I want to do is to save them as individual files with filename as each.name (the structure has a name key) and export it via a download button zipped perhaps.. I was trying to use export-from-json package but not necessary.

Can you please help me please with the following

  1. How to capture each into a separate file and then
  2. How to zip them all and download it as a single file on the click of a button?

Is it possible without any hosting needs?

CodePudding user response:

This totally achievable on the client side !

A lib like JSZip can fit your needs! (Adding multiple files into a zip) , and you can use FileSaver to save the file locally !

const foo = {foo: 'foo'};
const bar = {bar: 'bar'};

const zip = new JSZip();

zip.file('foo.json', JSON.stringify(foo));
zip.file('bar.json', JSON.stringify(bar));

zip.generateAsync({type:"blob"}).then(function(content) {
    saveAs(content, "example.zip");
});
  • Related