Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected token: u JSON.parse() issue

I have read online that the unexpected token u issue can come from using JSON.parse(). On my iPhone 5 there is no problem, but on my Nexus 7 I get this sequence of errors:

enter image description hereView large

I realize this is a duplicate, but I am not sure how to solve this for my specific problem. Here is where I implement JSON.parse()

 $scope.fav = []; 

if ($scope.fav !== 'undefined') {
   $scope.fav = JSON.parse(localStorage["fav"]);
}
like image 696
benjipelletier Avatar asked Apr 22 '14 13:04

benjipelletier


People also ask

How do you handle JSON parsing error?

The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.

What is JSON parse error?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

What does this mean SyntaxError unexpected token in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.

What does it mean unexpected token?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.


1 Answers

Base on your updated question the if condition does not make sense, because you set $scope.fav to [] right before, so it can never be "undefined".

Most likely you want to have your test that way:

if (typeof localStorage["fav"] !== "undefined") {
  $scope.fav = JSON.parse(localStorage["fav"]);
}

As i don't know if there is a situation where localStorage["fav"] could contain the string "undefined" you probably also need test for this.

if (typeof localStorage["fav"] !== "undefined"
    && localStorage["fav"] !== "undefined") {
  $scope.fav = JSON.parse(localStorage["fav"]);
}
like image 131
t.niese Avatar answered Sep 17 '22 17:09

t.niese