我有以下代码,让用户下载数据字符串在csv文件。

exportData = 'data:text/csv;charset=utf-8,';
exportData += 'some csv strings';
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

它工作得很好,如果客户端运行代码,它会生成空白页,并开始下载csv文件中的数据。

我试着用JSON对象来做这个

exportData = 'data:text/json;charset=utf-8,';
exportData += escape(JSON.stringify(jsonObject));
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

但是我只看到一个页面,上面显示了JSON数据,没有下载它。

我进行了一些研究,这一个声称工作,但我没有看到我的代码有任何不同。

我在代码中遗漏了什么吗?

谢谢你阅读我的问题。


当前回答

你可以尝试使用:

原生JavaScript API的Blob构造函数和 FileSaver.js saveAs()方法

根本不需要处理任何HTML元素。

var data = {
    key: 'value'
};
var fileName = 'myData.json';

// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
    type: 'application/json'
});

// Save the file
saveAs(fileToSave, fileName);

如果你想漂亮地打印JSON,根据这个答案,你可以使用:

JSON.stringify(data,undefined,2)

其他回答

    downloadJsonFile(data, filename: string){
        // Creating a blob object from non-blob data using the Blob constructor
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        // Create a new anchor element
        const a = document.createElement('a');
        a.href = url;
        a.download = filename || 'download';
        a.click();
        a.remove();
      }

你可以使用Blob轻松地自动下载文件,并在第一个参数downloadJsonFile中传输它。Filename是要设置的文件名。

链接的下载属性是新的,在Internet Explorer中是不支持的(见这里的兼容性表)。对于这个问题的跨浏览器解决方案,我想看看FileSaver.js

const exportToJson = (data: {}) =>{ const link = document.createElement("a"); 链接。href = 数据:text / json; charset = utf8, $ {encodeURIComponent (JSON.stringify(数据)};链接。下载= 'example.json';link.click ();}

如果你不想要一个什么都不做的随机元素,请确保在创建链接后清理干净。

对于那些只针对现代浏览器的人来说,简单、干净的解决方案:

function downloadTextFile(text, name) {
  const a = document.createElement('a');
  const type = name.split(".").pop();
  a.href = URL.createObjectURL( new Blob([text], { type:`text/${type === "txt" ? "plain" : type}` }) );
  a.download = name;
  a.click();
}

downloadTextFile(JSON.stringify(myObj), 'myObj.json');

这将是一个纯JS版本(改编自牛仔):

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);

http://jsfiddle.net/sz76c083/1