How to use localStorage with Object

Please can anyone understand why I need to do JSON.stringify(localStorage.setItem('data'))

; and then use JSON.parse(localStorage.getItem('data'))

before I can get my data object back.

+3


source to share


4 answers


In short: since local storage can only store strings.

The longer answer is that objects are complex data structures that, under the hood, are made up of references to different parts of computer memory. You can't just flush them to the storage area, because the data won't exist in those parts of memory when you read the data back.



So you need to serialize the data somehow.

A local server can be written to do this automatically, but only under certain circumstances. This is not the case, you have to do it manually, which means that you have to know what you are doing so that (a) if you lose data, it is not because the local API was strange and mysterious, and (b) you can choose between memory efficiency (localStorage gives you limited space) and simple (just using JSON.stringify

).

+4


source


Go to developer tools (f12 in browser) -> Application> Locat Storage -> Any page here.



You can see that all the elements here are just strings. If you want to store object

in local storage you need to convert it to string ( JSON.stringify

) and if you want to use your object again you need to convert it back to object ( JSON.parse

)

+1


source


Local storage is created to store strings as key pairs. You can store the object by serializing it as a string, for example

var object = {name:'somename'}
var string = JSON.stringify(object); // serialise as string
localStorage.setItem("name", string); // save string
var name = localStorage.getItem("name"); // for retrieving as string
var retrievedObj = JSON.parse(name) // for parse into object

      

0


source


LocalStorage stores data as strings. If you save the object, it will save as '[object Object]'

, because LocalStorage will call .toString()

on the object.

-2


source







All Articles