6

Please can someone make it clear why i need to do JSON.stringify(localStorage.setItem('data')); and then use JSON.parse(localStorage.getItem('data')) before i can get back my data object.

4 Answers 4

7

In short: Because local storage can only store strings.

The longer answer is that Objects are complex data structures which, under the hood, consist of references to different parts of the computer's memory. You can't just dump them to a storage area because the data won't exist at those parts of the memory when you read the data back.

Thus you need to serialise the data somehow.

The localStorage API could have been written to do this automatically, but only under some circumstances. It wasn't, you have to do it manually, which means you are forced to know what you are doing so that (a) if you lose data it isn't due to the localStorage API being weird and mysterious and (b) you can choose between being memory efficient (localStorage gives you limited space) and being simple (just using JSON.stringify).

Sign up to request clarification or add additional context in comments.

Comments

3

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

You can see that all the items here are just strings. If you want to store an object in the Local Storage, you need to convert it to string (JSON.stringify), and when you want to use your object again, you have to convert it back to an object (JSON.parse)

Comments

1

Local storage is made for storing strings as key value pairs. You can store an object by serialising it as a string, e.g.,

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

Comments

-2

LocalStorage saves data in the form of strings. If you save an object it will save as '[object Object]' because LocalStorage will call .toString() on the object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.