在HTML5 localStorage中存储对象

JavaScript

小哥Stafan

2020-03-09

我想在HTML5中存储一个JavaScript对象localStorage,但是我的对象显然正在转换为字符串。

我可以使用来存储和检索原始JavaScript类型和数组localStorage,但是对象似乎无法正常工作。应该吗

这是我的代码:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
    console.log('  ' + prop + ': ' + testObject[prop]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);

控制台输出为

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

在我看来,该setItem方法是在存储输入之前将输入转换为字符串。

我在Safari,Chrome和Firefox中看到了这种行为,因此我认为这是我对HTML5 Web存储规范的误解,而不是浏览器特定的错误或限制。

I've tried to make sense of the structured clone algorithm described in http://www.w3.org/TR/html5/infrastructure.html. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???)

Is there an easy workaround?


Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111. So this question is no longer 100% valid, but the answers still may be of interest.

第182篇《在HTML5 localStorage中存储对象》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
前端Tom 2020.03.09

要存储对象,您可以写一个字母,用它来将对象从字符串传送到对象(可能没有意义)。例如

var obj = {a: "lol", b: "A", c: "hello world"};
function saveObj (key){
    var j = "";
    for(var i in obj){
        j += (i+"|"+obj[i]+"~");
    }
    localStorage.setItem(key, j);
} // Saving Method
function getObj (key){
    var j = {};
    var k = localStorage.getItem(key).split("~");
    for(var l in k){
        var m = k[l].split("|");
        j[m[0]] = m[1];
    }
    return j;
}
saveObj("obj"); // undefined
getObj("obj"); // {a: "lol", b: "A", c: "hello world"}

如果您使用用于拆分对象的字母,此技术将引起一些故障,这也是非常实验性的。

樱Davaid 2020.03.09

对于愿意设置和获取键入属性的Typescript用户:

/**
 * Silly wrapper to be able to type the storage keys
 */
export class TypedStorage<T> {

    public removeItem(key: keyof T): void {
        localStorage.removeItem(key);
    }

    public getItem<K extends keyof T>(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);
    }

    public setItem<K extends keyof T>(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);
    }
}

用法示例

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}
}

const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");
乐卡卡西 2020.03.09

您可以使用ejson将对象存储为字符串。

EJSON是JSON的扩展,以支持更多类型。它支持所有JSON安全类型,以及:

所有EJSON序列化也是有效的JSON。例如,带有日期和二进制缓冲区的对象将在EJSON中序列化为:

{
  "d": {"$date": 1358205756553},
  "b": {"$binary": "c3VyZS4="}
}

这是我使用ejson的localStorage包装器

https://github.com/UziTech/storage.js

我在包装器中添加了一些类型,包括正则表达式和函数

Eva猿猿 2020.03.09

建议使用抽象库来实现此处讨论的许多功能以及更好的兼容性。很多选择:

木嘢 2020.03.09

另一种选择是使用现有插件。

例如,persisto是一个开源项目,它提供了一个到localStorage / sessionStorage的简单接口,并自动保持表单字段(输入,单选按钮和复选框)的持久性。

持久功能

(免责声明:我是作者。)

Mandy宝儿 2020.03.09

有一个很棒的库,其中包含许多解决方案,因此它甚至支持称为jStorage的旧版浏览器。

您可以设置一个对象

$.jStorage.set(key, value)

并轻松检索

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")
Tony老丝 2020.03.09

扩展存储对象是一个了不起的解决方案。对于我的API,我为localStorage创建了一个Facade,然后在设置和获取时检查它是否为对象。

var data = {
  set: function(key, value) {
    if (!key || !value) {return;}

    if (typeof value === "object") {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  },
  get: function(key) {
    var value = localStorage.getItem(key);

    if (!value) {return;}

    // assume it is an object that has been stringified
    if (value[0] === "{") {
      value = JSON.parse(value);
    }

    return value;
  }
}
LEY村村 2020.03.09

变体的小改进

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

Because of short-circuit evaluation, getObject() will immediately return null if key is not in Storage. It also will not throw a SyntaxError exception if value is "" (the empty string; JSON.parse() cannot handle that).

LEYAItachi 2020.03.09

您可能会发现使用以下方便的方法扩展Storage对象很有用:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
}

这样,即使在API下仅支持字符串,您也可以获得真正想要的功能。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android