27

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.

1

5 Answers 5

46

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>
Sign up to request clarification or add additional context in comments.

5 Comments

How or when is generateDownloadJsonUri() called
I have used on constructor because i had this.resJsonResponse ready. you should call it after you have Json Response ready.
It downloads html file for me, instead of json data
May be you should try with Blob.
I didn't add the download attribute to <a> and was struggling to find out why its not working.That's needed!
21

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);
}

Comments

6

I had some problems when my json was so big, I added a Blob object in the Ankur Akvaliya 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;
}

Comments

2

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

Import statement is needed:

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;
}

1 Comment

Please edit your answer to include some explanation. Code-only answers do very little to educate future SO readers. Your answer is in the moderation queue for being low-quality.
0

You can do this using bypassSecurityTrustUrl() method from DomSanitizer.

app.component.ts

export class AppComponent {
  downloadUrl;
  filename = "";
  constructor(private sanitizer: DomSanitizer) {
    this.generateUrl();
  }

  generateUrl() {
    var res = { appname: "ABCD", appid: 1234 };
    this.filename = res.appname + res.appid;
    var data = JSON.stringify(res);
    var url = this.sanitizer.bypassSecurityTrustUrl(
      "data:text/json;charset=UTF-8," + encodeURIComponent(data)
    );
    this.downloadUrl = url;
  }
}

app.component.html

<a [href]="downloadUrl" download="{{filename}}.json">Download</a>

Note that it is only the code snippet that required for Json file creation and linking with a download link.

Also, you can keep the filename as your wish. Currently, the filename is created using the json data.

If you are interested to check the live demo then you can go with the following link.

https://codesandbox.io/s/download-json-angular-k9fvz?file=/src/app/app.component.ts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.