如何使用多数组启动localStorage

时间:2012-12-25 21:16:51

标签: javascript local-storage

我通过尝试修改我的本地存储而浪费了很多时间。

最初我像这样启动它

localStorage.setItem('bipme','{"modules": []}');

它有效,但知道我需要这个例子

{
    "modules" : [
        {
            "id" : "0",
            "pseudo" : "Titi",
            "mode" : "gps",
            "perimetre" : "3",
            "distance" : "1",
            "start" : "2012-09-23 08:00:00",
            "refresh" : "08:20:00",
            "last" : "2012-09-23 08:00:00"
        },
        {
            "id" : "1",
            "pseudo" : "Toto",
            "mode" : "phone",
            "perimetre" : "10",
            "distance" : "0",
            "start" : "2012-09-23 08:00:00",
            "refresh" : "08:20:00",
            "last" : "2012-09-23 08:00:00"
        },
        {
            "id" : "2",
            "pseudo" : "Tete",
            "mode" : "gps",
            "perimetre" : "5",
            "distance" : "5",
            "start" : "2012-08-23 08:00:00",
            "refresh" : "10:20:00",
            "last" : "2012-09-23 08:00:00"
        }
    ],
    "modulesIndex" : 0,

    "watchPosition" : [
        {
            "id" : "0",
            "pseudo" : "Antoine",
            "phone" : "+41781234567",
            "date" : "2012-05-01 17:20:00"
        },
        {
            "id" : "1",
            "pseudo" : "Barbara",
            "phone" : "+41781234567",
            "date" : "2012-05-27 17:20:00"
        }
    ]
}

然后,我尝试了这个

localStorage.setItem('bipme','{"modules":[]},{"modulesIndex":0},{"watchPosition":[]}');

但现在我总是收到此错误消息

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
[Break On This Error]   

var objJSON = JSON.parse(localStorage.getItem('bipme'));

然后,我现在如何才能正确启动本地存储

感谢

2 个答案:

答案 0 :(得分:1)

设计模式是,您使用JSON stringify到要存储的对象。例如:

var objs = {
  modules : [
    {
        "id" : "0",
        "pseudo" : "Titi",
        "mode" : "gps",
        "perimetre" : "3",
        "distance" : "1",
        "start" : "2012-09-23 08:00:00",
        "refresh" : "08:20:00",
        "last" : "2012-09-23 08:00:00"
    }]
};
localStorage.setItem('bipme', JSON.stringify(objs));

答案 1 :(得分:0)

你有多个物品。如果这是你想要的,你需要使用方括号作为数组:

localStorage.setItem('bipme','{"modules":[]},{"modulesIndex":0},{"watchPosition":[]}');
// Should be:
localStorage.setItem('bipme','[{"modules":[]},{"modulesIndex":0},{"watchPosition":[]}]');

如果您希望modulesIndex等成为同一个对象的一部分,那么就不要关闭该对象:

localStorage.setItem('bipme','{"modules":[],"modulesIndex":0,"watchPosition":[]}');

我相信你已经在评论中解决了这个问题。

相关问题