1

我试图修改我的本地存储浪费了很多时间。

最初我像这样启动它

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'));

那么现在我该如何正确启动我的本地存储

感谢

4

2 回答 2

1

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

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));
于 2012-12-27T05:35:56.483 回答
0

你在那里有多个对象。如果这是您想要的,则需要对数组使用方括号:

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

如果您打算modulesIndexetc. 成为同一对象的一部分,那么只需不要关闭该对象:

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

我相信你已经在你的评论中解决了。

于 2012-12-25T21:34:31.237 回答