【问题标题】:Saving a Javascript object to a file将 Javascript 对象保存到文件中
【发布时间】:2013-12-27 16:10:23
【问题描述】:

我需要将 Javascript 对象保存到文件中,以便可以轻松地将其重新加载到变量中、修改并最终重新保存。这在 Javascript 中是否可行,如果可行,最好的方法是什么。例如,如果我有:

o = {"test": 2};

如何将其保存到文件、加载、修改和保存?与 Python 中的 pickle 完全一样。

谢谢。

【问题讨论】:

  • 仅使用 javascript 是不可能的。你能做的最好的就是使用 localStorage 但这不是永久存储
  • 您需要序列化对象并将结果字符串发送到能够由此创建文件的脚本语言(如 Java、PHP 等)。
  • 你为什么要烧水...?无法重新保存
  • 也许您想要新的FileSystem APIs?虽然我不会把它放在 feasible 的括号中

标签: javascript file object save


【解决方案1】:

尽管所有的答案都是相反的,但这确实是可能的。但是它受到浏览器支持的限制。您可以在最新版本的 Chrome 等中使用新的FileSystem APIs

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");
});

由于您只希望这些文件供您自己使用,因此这种沙盒方法将起作用。您还需要跳过一些障碍(请求配额、创建 Blob 对象),但链接文章中已涵盖这些内容,并且都取决于您的要求。

【讨论】:

  • 值得从您发布的链接中强调:“2014 年 4 月,在 public-webapps 上宣布其他浏览器不考虑文件系统 API 规范。目前,该 API 是特定于 Chrome 的而且它不太可能被其他浏览器实现,并且不再被 W3C 标准化。”
【解决方案2】:

如果你的字面意思是一个文件,这在客户端是不可能的。但是,如果它只是您想要存储和调用的数据,那么如果它很小,您可以使用 cookie。 http://www.sitepoint.com/how-to-deal-with-cookies-in-javascript/

如果它更大,您必须使用 HTML5 LocalStorage。但是,这仅适用于较新的浏览器。

你可以这样做来做一个访问计数器:

//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 等编写的服务器端脚本......

【讨论】:

  • 仅供参考,您的示例不符合书面要求。你必须先 JSON.Stringify(o) 才能存储它,因为 localStorage 只是字符串值。
【解决方案3】:

您可以使用元素的“下载”属性保存文件。 这是以编程方式完成的:

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2016-04-21
    • 2019-05-19
    • 2011-05-17
    相关资源
    最近更新 更多