Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected token u in JSON at position 0

when I'm try to convert string to object I get error ``:

Unexpected token u in JSON at position 0

Service

setUser : function(aUser){ 
    //sauvegarder User       
    localStorage.setItem('User', JSON.stringify(aUser));
},

getUser : function(){
    //récuperer User      
    return JSON.parse(localStorage.getItem('User'));
}
like image 812
nevergiveup Avatar asked May 24 '16 14:05

nevergiveup


1 Answers

The first thing to do is to look at what you're trying to parse. My guess is that you'll find it's "undefined", which is invalid JSON. You're getting undefined because you haven't (yet) saved anything to that key in local storage. undefined is then converted to the string "undefined" which JSON.parse can't parse.

I usually store and retrieve things in local storage like this:

Storing (just like yours):

localStorage.setItem("key", JSON.stringify(thing));

Retrieving (this is different):

thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
    // There wasn't one, do whatever is appropriate
}

That way, I'm always parsing something valid.

like image 118
T.J. Crowder Avatar answered Sep 21 '22 04:09

T.J. Crowder