我通过PHP序列化的json_encode有一个数组:
json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
// output json: {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
我尝试在Javascript中解码:
JSON.parse('{"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}');
然后我不明白为什么我会收到错误“Uncaught SyntaxError:Unexpected token w”? PHP和Javascript JSON解析器有区别吗?
答案 0 :(得分:4)
问题是因为您正在使用JSON.parse()并将JSON字符串括在单引号中。
所以你的转义正则表达式字符串在外部字符串文字(单引号)的解释中没有转义,然后在解释字符串pattern
(双引号)的值时混淆,最终导致JavaScript试图破译“\ w”。
以下示例,模仿PHP将JSON逐字渲染为声明,在JS控制台中正常工作:
var json = {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
如果你想使用JSON.parse,你必须首先在PHP中双重转义你的JSON字符串
$json = json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
$json = str_replace('\', '\\', $json);
// output json: {"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}
然后,在JS:
var json = JSON.parse('{"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}')