Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse() problem with regular expression values

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

like image 592
BaggersIO Avatar asked Mar 07 '11 14:03

BaggersIO


People also ask

What happens if JSON parse fails?

Copied! We call the JSON. parse method inside of a try/catch block. If passed an invalid JSON value, the method will throw an error, which will get passed to the catch() function.

Is JSON parse blocking or not?

A function that does not accept a callback or return a promise blocks until it returns a value. So yes it JSON. parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded.

What does JSON parse () method do?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.


2 Answers

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.

like image 150
Pointy Avatar answered Nov 15 '22 03:11

Pointy


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?

like image 41
ThiefMaster Avatar answered Nov 15 '22 04:11

ThiefMaster