最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I escape backslashes in JSON? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jun 13, 2010 at 23:57 peatbpeatb 4352 gold badges5 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 16

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)

  1. 暂无评论