0

A problem. Again. Here is the code:

if(localStorage.getItem("temporaryArray")){
    var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray"));
}else{
    var temporaryArray = [];
}

So basically what it does is that when a new page is loaded I don't want to reset the array because later in the code I assign something to this array in localStorage. So what I'm trying to say is that if you can get this item, then when the code is loaded again assign this variable to the localStorage item. Else, just set it to an empty array. But here is the error I'm getting because the array is currently empty(I think that's the reason why):

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at main.js:61

Any help would be very much appreciated.

5
  • 1
    show how you set temporaryArray - my guess is, you are not using JSON.stringify - because of the o in [object Object] Commented Jun 9, 2017 at 10:29
  • When you set value, use JSON.stringify. If not, [object Object] will be set and hence Unexpected token o in JSON at position 1 Commented Jun 9, 2017 at 10:30
  • snap @Rajesh :p Commented Jun 9, 2017 at 10:31
  • @Rajesh When I set the values I have been using JSON.stringify Commented Jun 9, 2017 at 10:49
  • @Rajesh Hello everyone I've fixed it! It was showing [object Object] for some reason so I went into the console and set the localStorage item to an empty string and now it's fixed. Thank you everyone! Commented Jun 9, 2017 at 10:55

1 Answer 1

1

If a method invocation fails, it usually helps to look at what the input to the function is. I would recommend doing console.log(localStorage.getItem("temporaryArray")) before the JSON.parse() call to see what the problem is.

What I would guess the source of the problem is, is that at some point you are calling localStorage.setItem("temporaryArray",value) and have forgotten to do JSON.stringify() on the value.

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

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.