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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With