假设我有一个看起来像这样的JavaScript对象:
var data = {
name: "cliff",
age: "34",
name: "ted",
age: "42",
name: "bob",
age: "12"
}
var jsonData = JSON.stringify(data);
我将其转换为JSON格式。如何将此JSON保存到本地文本文件中,以便可以在记事本等程序中打开它。
假设我有一个看起来像这样的JavaScript对象:
var data = {
name: "cliff",
age: "34",
name: "ted",
age: "42",
name: "bob",
age: "12"
}
var jsonData = JSON.stringify(data);
我将其转换为JSON格式。如何将此JSON保存到本地文本文件中,以便可以在记事本等程序中打开它。
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
浏览器 (Web API):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
这是我保存本地数据到文本文件的解决方案。
function export2txt() {
const originalData = {
members: [{
name: "cliff",
age: "34"
},
{
name: "ted",
age: "42"
},
{
name: "bob",
age: "12"
}
]
};
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {
type: "text/plain"
}));
a.setAttribute("download", "data.txt");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
<button onclick="export2txt()">Export data to local txt file</button>
JSON.stringify(originalData, null, 2)
的缩进提示。如果文件是JSON文件,则将文件命名为"data.json"应该更加合适。 - Patronauttype: "text/plain"
更改为:type: "application/json"
。 - WinEunuuchs2Unix这里有一个纯JS的解决方案。你可以使用HTML5 saveAs来实现。例如,这个库可能会有所帮助:https://github.com/eligrey/FileSaver.js
查看演示:http://eligrey.com/demos/FileSaver.js/
顺便说一下,没有关于JSON保存的信息,但是你可以将文件类型更改为"application/json"
并将格式更改为.json
。
import { saveAs } from 'file-saver'
let data = { a: 'aaa' , b: 'bbb' }
let blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
saveAs(blob, 'export.json')
我采用了dabeng的解决方案,并将其转录为类方法。
class JavascriptDataDownloader {
constructor(data={}) {
this.data = data;
}
download (type_of = "text/plain", filename= "data.txt") {
let body = document.body;
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([JSON.stringify(this.data, null, 2)], {
type: type_of
}));
a.setAttribute("download", filename);
body.appendChild(a);
a.click();
body.removeChild(a);
}
}
new JavascriptDataDownloader({"greetings": "Hello World"}).download();
[object Object]
的结果。 - Jack[object Object]
.. 我必须先调用JSON.stringify()
,然后传递该值,而不是对象本身。 - ne1410sa.click()
后,我们需要调用revokeObjectURL
方法来告诉浏览器不再保留对文件的引用:URL.revokeObjectURL(a.href)
。更多信息请参考:https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL。 - andreivictor