我需要将一个JavaScript对象保存到文件中,以便可以轻松地重新加载到变量中进行修改,并最终重新保存。在JavaScript中是否可行,如果是的话,最佳方法是什么?例如,如果我有:
o = {"test": 2};
如何将它保存到文件中,加载、修改并保存?就像Python中的pickle
一样。
谢谢。
我需要将一个JavaScript对象保存到文件中,以便可以轻松地重新加载到变量中进行修改,并最终重新保存。在JavaScript中是否可行,如果是的话,最佳方法是什么?例如,如果我有:
o = {"test": 2};
如何将它保存到文件中,加载、修改并保存?就像Python中的pickle
一样。
谢谢。
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 1024, function(fs) {
fs.root.getFile('mystorage.txt', {create: true, exclusive: true}, function(file) {
file.createWriter(function(writer) {
var blob = new Blob(["putdatahere"], {type: 'text/plain'});
writer.write(blob);
});
});
}, function() {
console.log("Could not access file system");
});
如果你只需要自己使用文件,那么这种沙盒方法可以使用。但是,你需要进行更多步骤(请求配额,创建对象),但这些步骤在链接的文章中有详细说明,具体取决于你的要求。
//try to load the data
var o = localStorage.getItem("mydata");
//if the data is empty set the data
if(!o) o = {"test": 0};
//increment the test value inside of o by one each time
o.test++;
//save the data to local storage
localStorage.setItem("mydata", JSON.stringify(o));
http://diveintohtml5.info/storage.html
请注意,此方法仅适用于像Chrome这样的现代浏览器。
传统的方法是通过AJAX将其发送到使用PHP、Python、Ruby、Java等编写的服务器端脚本。
function saveJSON() {
let data = "Whatever it is you want to save";
let bl = new Blob([data], {
type: "text/html"
});
let a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = "data.json";
a.hidden = true;
document.body.appendChild(a);
a.innerHTML =
"someinnerhtml";
a.click();
}