将对象转换为JSON并在React中作为.json文件下载 [英] Converting Object into JSON and downloading as a .json file in React
问题描述
我有一个包含一些信息的javascript对象.
我想将其转换为JSON并将其下载为.json文件.
似乎我只能将JSON.stringify(obj)
转换为JSON
但是我实际上如何将其下载为.json文件?
I have a javascript object that contains some information.
I want to convert this into JSON and download it as a .json file.
Seems like I can just to JSON.stringify(obj)
to convert it into JSON
but how do I actually download it as a .json file?
推荐答案
如果您只是想通过JavaScript下载数据,则不确定这是否是特定于React的问题,但这是我使用的摘录,链接以下载数据内容,虚拟单击该元素,最后将其从DOM中删除.它应该同时支持现代浏览器和较旧的IE:
I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:
private exportToJson(objectData: SomeObject) {
let filename = "export.json";
let contentType = "application/json;charset=utf-8;";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
同样值得注意的是,在此SO中引用了问题.
It's also worth noting that there are a number of ways to approach this as cited in this SO question.
这篇关于将对象转换为JSON并在React中作为.json文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!