6

I have the following JSON string, encoded with PHP 5.2 json_encode():

{"foo":"\\."}

This JSON string is valid. You can check it out at http://www.jsonlint.com/

But the native JSON.parse() method (Chrome, Firefox), throws the following error, while parsing:

SyntaxError: Unexpected token ILLEGAL

Does anybody of you know, why I cannot parse escaped regular expression meta chars?

This example works:

{"foo":"\\bar"}

But this one fails also:

{"foo":"\\?"}

BTW: \. is just a simple test regular expression, which I want to run via javascript's RegExp object.

Thanks for your support,

Dyvor

1
  • 3
    It works for '{"foo":"\\\\?"}'. So it seems you have to "double escape" the characters. '{"foo":"\\bar"}' seems to work (it throws no error) but the result will be {foo: "ar"}. Commented Mar 7, 2011 at 14:47

3 Answers 3

9

It's "not working" because you're missing a key point: there are two string parses going on when you type into the Chrome console a line like:

JSON.parse('{"foo": "\\."}');

The first string parse happens when the JavaScript interpreter parses the string constant you're passing in to the "parse()" method. The second string parse happens inside the JSON parser itself. After the first pass, the double-backslash is just a single backslash.

This one:

{"foo":"\\bar"}

works because "\b" is a valid intra-string escape sequence.

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

2 Comments

+1 Pointy's right var test = {"foo":"\\bar"}; alert(JSON.stringify(test)); // alerts '{"foo":"\\bar"}'; var test2 = '{"foo":"\\bar"}'; alert(JSON.stringify(JSON.parse(test2))); // alerts '{"foo":"\bar"}';
@DefyGravity I don't understand what you're getting at there. -- oh OK :-)
2

It works for me in the firebug console.

>>> JSON.parse('"\\\\."');
"\."

which is correct as the json parser actually receives "\\.", i.e. an esacped backslashes and a dot.

Did the problem actually happend to you with the response coming from PHP? Or just in a "manual" test?

Comments

0

add an extra set of \\, as to why it works I'm not exactly sure.

JSON.parse('{"foo":"\\\\."}');

1 Comment

It works because there are two parses happening: the JavaScript parse of the string constant coded into the function call expression, and then the JSON parse of the resulting string.

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.