Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape backslashes in JSON?

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?

like image 701
peatb Avatar asked Jun 13 '10 23:06

peatb


1 Answers

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/

like image 129
Nick Craver Avatar answered Sep 28 '22 08:09

Nick Craver