Skip to content

本地存储localStorage 存储json对象存储格式问题 #18

Description

@LSYY888
var obj={"a":1,"b":2};
localStorage.setItem("temp2",obj);
typeof localStorage.getItem("temp2");也会返回String
localStorage.getItem("temp");却返回[object Object]

用localStorage.setItem()正确存储json对象方法是:存储前先用JSON.stringify()方法将json对象转换成字符串形式,如:

var obj={"a":1,"b":2};
obj=JSON.stringify(obj);
localStorage.setItem("temp2",obj);
typeof localStorage.getItem("temp2");返回String
localStorage.getItem("temp2");返回字符串格式:{"a":1,"b":2}

后续要操作该json对象,自然得将之前存储的json字符串先转成json对象再进行操作,如:

obj=JSON.parse(localStorage.getItem("temp2"));

操作完,存储信息前,记得再转换下格式:obj=JSON.stringify(obj);

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions