Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 to export/download json file

Tags:

I am using angular 2. I want to give functionality to download JSON file.

Like i have response with res = {bar : foo} then i want to create json file which will contain this response which can be download on button/anchor click.

Any help will be greatly appreciated.

like image 885
Ankur Akvaliya Avatar asked Feb 21 '17 07:02

Ankur Akvaliya


People also ask

How do I export a JSON file?

To export package JSON first open a package, find the Import/Export dropdown and press the Export button. After that, the browser will start a download. The exported JSON file is formatted so it will be easy to track the difference between such files.


1 Answers

It was simpler than expected.

constructor(private sanitizer: DomSanitizer){}      generateDownloadJsonUri() {         var theJSON = JSON.stringify(this.resJsonResponse);         var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));         this.downloadJsonHref = uri;     } 

in the template include

<a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a> 
like image 100
Ankur Akvaliya Avatar answered Sep 30 '22 08:09

Ankur Akvaliya