带有正则表达式值的JSON.parse()问题 [英] JSON.parse() problem with regular expression values

查看:296
本文介绍了带有正则表达式值的JSON.parse()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON字符串,用PHP 5.2 json_encode()编码:

I have the following JSON string, encoded with PHP 5.2 json_encode():

{"foo":"\\."}

此JSON字符串有效.您可以在 http://www.jsonlint.com/

This JSON string is valid. You can check it out at http://www.jsonlint.com/

但是,原生JSON.parse()方法(Chrome,Firefox)在解析时会引发以下错误:

But the native JSON.parse() method (Chrome, Firefox), throws the following error, while parsing:

SyntaxError: Unexpected token ILLEGAL

您知道吗,为什么我无法解析转义的正则表达式元字符?

Does anybody of you know, why I cannot parse escaped regular expression meta chars?

此示例有效:

{"foo":"\\bar"}

但是这个失败了:

{"foo":"\\?"}

顺便说一句:\.只是一个简单的测试正则表达式,我想通过javascript的RegExp对象运行它.

BTW: \. is just a simple test regular expression, which I want to run via javascript's RegExp object.

感谢您的支持,

Dyvor

推荐答案

这是无效的",因为您缺少一个关键点:在键入Chrome控制台的行如下:

It's "not working" because you're missing a key point: there are two string parses going on when you type into the Chrome console a line like:

JSON.parse('{"foo": "\\."}');

第一个字符串解析发生在JavaScript解释器解析您要传递给"parse()"方法的字符串常量时. second 字符串解析发生在JSON解析器本身内部.第一次通过后,双反斜杠只是一个单反斜杠.

The first string parse happens when the JavaScript interpreter parses the string constant you're passing in to the "parse()" method. The second string parse happens inside the JSON parser itself. After the first pass, the double-backslash is just a single backslash.

这个:

{"foo":"\\bar"}

之所以起作用,是因为"\ b"是有效的字符串内转义序列.

works because "\b" is a valid intra-string escape sequence.

这篇关于带有正则表达式值的JSON.parse()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆