Javascript 如何在 JSON 中转义反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3034385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I escape backslashes in JSON?
提问by peatb
I am using Firefox's native JSON.parse() to parse some JSON strings that include regular expressions as values, for example:
我正在使用 Firefox 的本机 JSON.parse() 来解析一些包含正则表达式作为值的 JSON 字符串,例如:
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).
上面的 '\d' 使用 JSON.parse() 抛出异常,但在我使用 eval 时工作正常(这是我试图避免的)。
What I want is to preserve the '\' in the regex - is there some other JSON-friendly way to escape it?
我想要的是在正则表达式中保留 '\' - 是否有其他一些 JSON 友好的方式来转义它?
采纳答案by Nick Craver
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/
你可以在这里测试一下:http: //jsfiddle.net/h3rzE/

