开发者

How do I escape backslashes in JSON?

开发者 https://www.devze.com 2023-01-03 13:43 出处:网络
I am using Firefox\'s native JSON.parse() to parse some JSON strings that include regular expressions as value开发者_运维知识库s, for example:

I am using Firefox's native JSON.parse() to parse some JSON strings that include regular expressions as value开发者_运维知识库s, 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?


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消