Angular2 to export / download json file

I am using angular 2. I want to provide functionality for loading a JSON file.

Like I have an answer with res = {bar: foo}, then I want to create a json file that will contain this answer, which can be loaded by pressing the button / anchor.

Any help would be greatly appreciated.

+5
source share
4 answers

It was just then, I was expecting

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

 <a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a> 
+8
source

I had some problems when my json was so big, I added a Blob object in Ankur Akvaliya's answer and it works !!

 generateDownloadJsonUri() { let theJSON = JSON.stringify(this.resJsonResponse); let blob = new Blob([theJSON], { type: 'text/json' }); let url= window.URL.createObjectURL(blob); let uri:SafeUrl = this.sanitizer.bypassSecurityTrustUrl(url); this.downloadJsonHref = uri; } 
+1
source

You can use DomSanitizer: https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

Import instruction required:

 import {enter code here DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser'; 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; } 
0
source

Pure JavaScript will do the job.

 downloadJson(myJson){ var sJson = JSON.stringify(myJson); var element = document.createElement('a'); element.setAttribute('href', "data:text/json;charset=UTF-8," + encodeURIComponent(sJson)); element.setAttribute('download', "primer-server-task.json"); element.style.display = 'none'; document.body.appendChild(element); element.click(); // simulate click document.body.removeChild(element); } 
0
source

Source: https://habr.com/ru/post/1264489/


All Articles