1

Can any object be stored in a DOM Storage?

When I do the following:

// where val is a string and response is an array of objects.
sessionStorage.results= { val: response };

When I inspect value of sessionStorage.results I get "[object Object]"

Can I store objects like that? Or does Storage only stores strings?

dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

1 Answers1

7

You can only store strings in any type of (DOM-)storage. To store data objects (plain: no circular references, no special constructors) you can convert them to JSON and back from a string to restore them. See also this answer (improvement).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Am I blind? I can't find a question on SO to link, concerning that JSON-text transformation. There must be one! – Bergi May 17 '12 at 15:15
  • Something like this? http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery – dev.e.loper May 17 '12 at 15:29
  • Nah, I meant questions (like this) where users try to store objects in `localStorage` and get explanations of `JSON.stringify` and `.parse` in that context. – Bergi May 17 '12 at 15:36
  • yeah, really blind: http://stackoverflow.com/q/2010892/1048572 and http://stackoverflow.com/q/3357553/1048572 – Bergi May 17 '12 at 15:39