JSON.parse() problem with regular expression value

2020-07-10 08:08发布

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

3条回答
够拽才男人
2楼-- · 2020-07-10 08:53

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

JSON.parse('{"foo":"\\\\."}');
查看更多
不美不萌又怎样
3楼-- · 2020-07-10 08:56

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?

查看更多
贪生不怕死
4楼-- · 2020-07-10 08:59

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.

查看更多
登录 后发表回答