Angular2导出/下载json文件

时间:2017-02-21 07:00:01

标签: javascript json angular download export

我正在使用angular 2.我想提供下载JSON文件的功能。

就像我有res = {bar:foo}的回复,然后我想创建包含此响应的json文件,可以在按钮/锚点击下载。

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:18)

比预期的要简单。

df2 dataframe
模板中的

包括

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 :(得分:5)

纯JavaScript将完成这项工作。

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

答案 2 :(得分:3)

当我的json如此之大时,我遇到了一些问题,我在Ankur Akvaliya的答案中添加了一个Blob对象,它有效!!

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

答案 3 :(得分:0)

您可以使用DomSanitizer: https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

需要导入语句:

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