user2543382
user2543382

Reputation:

JSON.parse throwing illogical Syntax Error: Unexpected token

I have a problem with parsing the json string passed from a method in PHP over an AJAX call. The string is

[{"type":"successful","message":"Prijava uspe\u0161na!"}] 

When I try to parse it in javascript with JSON.parse(the string), I get an Unexpected token error in my console.

There is no problem when I execute this on my localhost nothing is wrong even though I get the same response from the PHP script.

When I try the following in the success function of the ajax

console.log(message);
console.log(JSON.stringify(message));
console.log(JSON.parse(message));

I get this

[{"type":"successful","message":"Prijava uspe\u0161na!"}]  login:102
"\r\n\r\n[{\"type\":\"successful\",\"message\":\"Prijava uspe\\u0161na!\"}]\r\n\r\n" login:104
Uncaught SyntaxError: Unexpected token  login:104

And line 104 (well not really, the console points at it):

console.log(JSON.parse(message));

I've tried replacing \r\n, ended up the same

I am really confused...

Upvotes: 0

Views: 1263

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Your JSON has a BOM, which is not a valid token.

Ensure that whatever is sending your JSON is encoding it correctly without this BOM.

Upvotes: 1

Related Questions