JSON.parse () problem with regular expressions

I have the following JSON string encoded using 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) causes the following error when parsing:

 SyntaxError: Unexpected token ILLEGAL 

Do any of you know why I cannot parse metacharacters with a regular expression?

This example works:

 {"foo":"\\bar"} 

But this also fails:

 {"foo":"\\?"} 

BTW: \. is just a simple test regular expression that I want to run through a JavaScript RegExp object.

Thanks for your support,

Dyvor

+6
json javascript firefox google-chrome regex
source share
3 answers

It doesn’t work because you are missing a keyword: after entering the Chrome console, lines two are built as:

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

The first parsing occurs when the JavaScript interpreter parses the string constant that you pass to the parse () method. The second line parsing takes place inside the JSON parser itself. After the first pass, a double backslash is just one backslash.

This:

 {"foo":"\\bar"} 

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

+9
source share

It works for me in the firebug console.

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

which is correct since the json parser actually gets "\\." , i.e. evacuated backslashes and period.

Was the problem really related to your PHP response? Or just in a "manual" test?

+1
source share

add an extra set \\ why it works, I'm not quite sure.

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

All Articles