从浏览器下载 JSON 对象作为文件 [英] Download JSON object as a file from browser

查看:34
本文介绍了从浏览器下载 JSON 对象作为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码让用户下载 csv 文件中的数据字符串.

I have the following code to let users download data strings in csv file.

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

如果客户端运行代码,它会生成空白页面并开始下载 csv 文件中的数据.

It works just fine that if client runs the code it generates blank page and starts downloading the data in csv file.

所以我试着用 JSON 对象来做这个

So I tried to do this with JSON object like

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

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

But I see only a page with the JSON data displayed on it, not downloading it.

我进行了一些研究和这个 声称可以工作,但我看不出我的代码有什么不同.

I went through some research and this one claims to work but I don't see any difference to my code.

我的代码中是否遗漏了什么?

Am I missing something in my code?

感谢您阅读我的问题:)

Thanks for reading my question:)

推荐答案

这是我为我的应用程序解决的方法:

This is how I solved it for my application:

HTML:<a id="downloadAnchorElem" style="display:none"></a>

JS(纯 JS,这里不是 jQuery):

JS (pure JS, not jQuery here):

var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href",     dataStr     );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();

在这种情况下,storageObj 是您要存储的 js 对象,而scene.json"只是结果文件的示例名称.

In this case, storageObj is the js object you want to store, and "scene.json" is just an example name for the resulting file.

与其他提议的方法相比,这种方法具有以下优点:

This approach has the following advantages over other proposed ones:

  • 无需点击任何 HTML 元素
  • 结果将根据您的需要命名
  • 不需要 jQuery

我不需要显式点击就需要这种行为,因为我想在某个时候从 js 自动触发下载.

I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.

JS 解决方案(不需要 HTML):

JS solution (no HTML required):

  function downloadObjectAsJson(exportObj, exportName){
    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
  }

这篇关于从浏览器下载 JSON 对象作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆