Home Ask Login Register

Developers Planet

Your answer is one click away!

Vlad2000Andrei February 2016

JSON.parse() from localStorage issue

I am currently working on a little browser game and I am using the HTML localStorage to save some data.

The problem: I have an empty array that i will later .push() some data into. I am storing this array in the localStorage but when i try to read from the local storage it doesn't work.

The Chrome Developer Tools console is giving me this error: "Uncaught SyntaxError: Unexpected token u" when trying to parse the data from localStorage.

Here's the code i am using:

var allContracts = [];
localStorage["allContracts"] = JSON.stringify(allContracts);

allContracts = JSON.parse(localStorage["allContracts"]);

There is more code than this but none of it is interacting with these in any way.

Is there a quirk with localStorage or JSON that i am not aware of and is causing this? (i am not very familiar with JSON or localStorage) Should i be doing this a different way? Or am i just missing an obvious mistake?

Thanks in advance :)


Andrew February 2016

You should use

localStorage.setItem('allContracts', JSON.stringify(allContracts));

More details here: https://developer.mozilla.org/en-US/docs/Web/API/Storage

baldmark February 2016

I have only just started using localStorqage myself, but it looks like you should be using window.localStorage.setItem() and window.localStorage.getItem()

Marcos Pérez Gude February 2016

The best way is to use the methods that the interface of localStorage serves to you. It have setItem() and getItem() methods, so why not use to safe yourself?

var allContracts = [];
// setter
localStorage.setItem("allContracts",  JSON.stringify(allContracts));
var allContracts = JSON.parse(localStorage.getItem("allContracts"));

With your piece of code, you are overriding the localStorage global object with your own values, so you lost the functionality.

You make this:

localStorage = [] // transform the default localstorage into an array

And you need this:

localStorage.setItem(key, value)

More info: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Post Status

Asked in February 2016
Viewed 2,513 times
Voted 10
Answered 3 times


Leave an answer

Quote of the day: live life