3

I'm trying out localStorage and JSON using a variety of browsers with this piece of code:

        function getStorage() {
            stored = JSON.parse(localStorage['test']);
            if (typeof stored == 'object') {return stored;}
        }

Chrome gives me the following error message: "Uncaught SyntaxError: Unexpected token u" for the first line inside the function body. For that same line, Safari says "SyntaxError: Unable to parse JSON string". Firefox does not give any error messages for that line.

Other JSON.parse examples (from books, etc) work fine in both Safari and Chrome. For instance, this one from "Pro JavaScript" by Nicholas Zakas:

            var jsonText = "{\"name\":\"Nicholas C. Zakas\", \"age\":29, \"author\":true }";
            var object = JSON.parse(jsonText);
            alert(object.name);  //"Nicholas C. Zakas"

No problem at all with getting that to work. Local storage also works fine in both.

I've also checked the encoding on all my files using file -I my file and all files, both my own and the ones from the above book, are encoded as filename.html: text/html; charset=us-ascii - so encoding doesn't seem to be the problem here.

This is perplexing. Thanks a lot for any help.

/ James

fullstackplus
  • 1,061
  • 3
  • 17
  • 31
  • What is the data you are storing in the local storage? Seems not to be conform json. – Fox32 Oct 09 '11 at 13:50
  • can we see the json string that you are trying to parse? – Baz1nga Oct 09 '11 at 14:08
  • Sure, here's the JSON string: `if (window.localStorage) { if (localStorage.length == 0) { json = {"test": ["foo", "bar"]} // json is a global variable window.localStorage.setItem("test", JSON.stringify(json)); } }` – fullstackplus Oct 09 '11 at 18:42
  • Did you try to use console.log(localStorage["test"]) to check the value that is stored? – Fox32 Oct 10 '11 at 07:20
  • Problem solved! Thanks for the advice on debugging the contents of localStorage directly. The bug was in the line `if (localStorage.length == 0)`. I had some other data in localStorage from previous apps, so `json` didn't get set to anything inside that conditional. Now I use `if (!localStorage['test']) {//set json}`. So much for Safari & Chrome - in Firefox 6.0.2 localStorage isn't working for different reasons: http://stackoverflow.com/questions/7355324/did-localstorage-just-break-in-firefox-6-0-2-on-mac – fullstackplus Oct 11 '11 at 14:55

2 Answers2

0

It's because the content of localStorage['test'] is undefined, hence the unexpected u.

jeremy
  • 9,965
  • 4
  • 39
  • 59
-2

Thanks for the advice on debugging the contents of localStorage directly. The bug was in the line if (localStorage.length == 0). I had some other data in localStorage from previous apps, so json didn't get set to anything inside that conditional.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265