'Uncaught SyntaxError: Unexpected token u' when using JSON.parse
javascript, jquery, json
Solution
Try
var users = localStorage.registeredUsers? JSON.parse(localStorage.registeredUsers) : [];
or if you don't like the ternary operator,
var users=[];
if(localStorage.registeredUsers){
users=JSON.parse(localStorage.registeredUsers);
}
might help
Problem
I'm using JSON.parse as a simple database on my computer with LocalStorage. It works smoothly until I'm doing the check of this "database"; heres the code for entering information to LocalStorage: ``` var users = JSON.parse(localStorage.registeredUsers); users.push({username:name, password:userpass, connected:false}); localStorage.registeredUsers = JSON.stringify(users); ``` and when I', having the check of that registeredusers I get the error "Uncaught SyntaxError: Unexpected token u": ``` var users = JSON.parse(localStorage.registeredUsers); if(users[userindex].connected) {.........} ``` The error points to the line with JSON.parse. I tried to figure it out with some similiar topics but couldnt find the way. The code that I push into the array of localstorage: ``` function regBtn(event) { event.preventDefault(); name=document.forms["regform"]["username"].value; userpass=document.forms["regform"]["password"].value; localStorage.username=name; localStorage.password=userpass; if(!(localStorage.registeredUsers)) { localStorage.registeredUsers = '[]'; } var users = JSON.parse(localStorage.registeredUsers); users.push({username:name, password:userpass, connected:false}); localStorage.registeredUsers = JSON.stringify(users); $('#mainContent').load('HomePage.html'); } ```