SessionStorage and json objects
Asked Answered
T

3

11
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?

Tonga answered 15/1, 2016 at 18:49 Comment(2)
No way to say without knowing what user contains. Looks like it's been already converted to a JSON string.Inaptitude
it's a hack but user: JSON.parse(user) would fix it. Go back to where user gets defined and fix it there though. Show all relevant codePinniped
C
29

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);
Croquet answered 15/1, 2016 at 21:37 Comment(0)
C
1

Set the item

sessionStorage.setItem('user', user)

Get the item

var item = sessionStorage.getItem('user')
var user = item ? JSON.stringify(item) : {}
Capsular answered 16/2, 2020 at 2:5 Comment(0)
E
1

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")}`)
Easton answered 23/6, 2020 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.