假设我有一个看起来像这样的javascript对象:
var data = {
name: "cliff",
age: "34",
name: "ted",
age: "42",
name: "bob",
age: "12"
}
var jsonData = JSON.stringify(data);
Run Code Online (Sandbox Code Playgroud)
我将其字符串化以转换为JSON.如何将此JSON保存到本地文本文件,以便我可以在记事本等中打开它.
Raf*_*ski 131
Node.js的:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Run Code Online (Sandbox Code Playgroud)
浏览器(webapi):
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');
Run Code Online (Sandbox Code Playgroud)
dab*_*eng 13
这是我将本地数据保存到txt文件的解决方案。
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);
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="export2txt()">Export data to local txt file</button>
Run Code Online (Sandbox Code Playgroud)
小智 6
这是纯js的解决方案。您可以使用html5 saveAs来实现。例如,该库可能会有所帮助:https
: //github.com/eligrey/FileSaver.js
查看演示:http
: //eligrey.com/demos/FileSaver.js/
PS没有有关json保存的信息,但是您可以将文件类型更改为"application/json"
并将其格式更改为.json
采取了大崩的解决方案,我将其转录为类方法。
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();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
98405 次 |
最近记录: |