SessionStorage and json objects

2020-07-10 07:38发布

user: {firstName: "loki", lastName: "ch"}

I am storing this user in session storage.

$window.sessionStorage.user = user;

when i retrieved it back using $window.sessionStorage.user, i got:

[object Object] 

I want in JSON. Any suggestions?

3条回答
倾城 Initia
2楼-- · 2020-07-10 08:07

Convert it to JSON before saving it.

$window.sessionStorage.user = JSON.stringify(user);

Then when you're loading it, parse the JSON.

var user = JSON.parse($window.sessionStorage.user);
查看更多
Fickle 薄情
3楼-- · 2020-07-10 08:08

Set the item

sessionStorage.setItem('user', user)

Get the item

var item = sessionStorage.getItem('user')
var user = item ? JSON.stringify(item) : {}
查看更多
可以哭但决不认输i
4楼-- · 2020-07-10 08:20

Apparently for Typescript users in React for example, You'll have to pass it as a string

JSON.parse(`${sessionStorage.getItem("session storage item name")}`)
查看更多
登录 后发表回答