Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token - due to double backslash

Tags:

json

I seem to have a strange problem, I get a "Uncaught SyntaxError: Unexpected token P" error. It is due to the double backslash. But double backslash is need to escape a backslash and this seems to be 100% valid JSON which is generated from php's json_encode function.

var urls = '{"MyApp\\Posts\\Post":"foo","MyApp\\Threads\\Thread":"bar"}';
obj = jQuery.parseJSON(urls);
like image 438
Tesla Avatar asked Oct 29 '25 12:10

Tesla


1 Answers

If you console.log(urls), you can see the string value that is passed to the JSON parser:

{"MyApp\Posts\Post":"foo","MyApp\Threads\Thread":"bar"}

However, \ is the escape character in JSON and \P is an invalid escape sequence.


"The problem" is that backslash is also the escape character in a JS string. If you want to produce a literal backslash in a JS string for JSON, you have to double escape it:

var urls = '{"MyApp\\\\Posts\\\\Post":"foo","MyApp\\\\Threads\\\\Thread":"bar"}';

That said, there is no value in having a string literal with JSON in JS. You can just use an object literal:

var urls = {"MyApp\\Posts\\Post":"foo","MyApp\\Threads\\Thread":"bar"};

Note: If the JSON is not in a string literal, but you get it as response from an Ajax call, for example, then

{"MyApp\\Posts\\Post":"foo","MyApp\\Threads\\Thread":"bar"}'

is valid JSON.

like image 200
Felix Kling Avatar answered Oct 31 '25 02:10

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!