Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download JSON array to file

What is the recommended way for the following:

An array of entities should be downloaded over a button. The button is called Download transactions and should do exactly that without forcing the user to "right click and 'save site as...'".

I have an entity Transaction and an array containing it.

Entity:

export class Transaction {
  title: string;
  category: string;
  period: string;
  value: string;
}

This was the last try I did to download this array as a file:

  exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    const fileURL = URL.createObjectURL(file);
    location.href = fileURL;
  }

This loads the tab containing the result in the current window, but as plain text and not as downloadable file.

I know that there are a LOT of questions about this topic, none I found worked for me. Any help is appreciated! :)

like image 752
codepleb Avatar asked Jan 20 '26 02:01

codepleb


1 Answers

the following function might be what you are looking for:

function download(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(blob, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

and then

exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    download(file,"fileName.json");
  }
like image 110
Yuval Perelman Avatar answered Jan 22 '26 19:01

Yuval Perelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!