views:

55

answers:

1

I am using Firefox's native JSON.parse() to parse some JSON strings that include regular expressions as values, for example:

var test = JSON.parse('{"regex":"/\\d+/"}');

The '\d' in the above throws an exception with JSON.parse(), but works fine when I use eval (which is what I'm trying to avoid).

What I want is to preserve the '\' in the regex - is there some other JSON-friendly way to escape it?

+2  A: 

You need to escape the escape backslashes already in there :) like this:

var test = JSON.parse('{"regex":"/\\\\d+/"}');

You can test it a bit here: http://jsfiddle.net/h3rzE/

Nick Craver
Thanks, that works a charm! Would you mind explaining why I need to escape the escapes though? I would have thought that escaping the "\b" once would be enough for the purposes of the parser... is there another layer of parsing going on behind the scenes that requires it?Also, thanks for the jsfiddle link - I was using the parser at http://json.parser.online.fr/ for testing, but when I tried the "\\\\d" it told me that one of the backslashes needs to be escaped!
peteb