论坛首页 AJAX版 GWT

Google JSON解析的两个正则,没看明白:(

浏览 332 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2008-05-06
http://gmodules.com/ig/modules/json.js?ts=040408
这两个正则不知何意:(
谁有兴趣去研究一下?

 function parse(text) {
      try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
//只允许某些申明符号,禁止运算元素;
//可非asii怎么办?{'value':"中文是合法的啊"}
//还有Eaeflnr-u   Eefnrtu可以理解  sa是什么呢?
            text.replace(/"(\\.|[^"\\])*"/g, ''))) &&//去掉字符串
          eval('(' + text + ')');
      } catch (e) {
        return false;
      }
    }
   
时间:2008-05-06
貌似一个简单的语法检查。
同时还要禁止运算逻辑?
   
0 请登录后投票
时间:2008-05-06
jindw 写道
貌似一个简单的语法检查。
同时还要禁止运算逻辑?


是这样的,你可以看看 http://www.json.org/json2.js
...
// In the second stage, we run the text against
// regular expressions that look for non-JSON patterns. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we want to reject all
// unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

                if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
...


至于中文,json.org 的规范中是要求用 \uXXXX 的形式(utf-8编码),不应该出现中文。
   
0 请登录后投票
时间:2008-05-06
先做了text.replace(/"(\\.|[^"\\])*"/g, ''),然后再test,中文应该允许。parse期望的输入是stringify的结果,stringify处理的对象属性名都变成了“name”:...
Eaeflnr-u 这些字符做什么用的?
   
0 请登录后投票
时间:2008-05-07
jindw 写道
http://gmodules.com/ig/modules/json.js?ts=040408
这两个正则不知何意:(
谁有兴趣去研究一下?

 function parse(text) {
      try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
//只允许某些申明符号,禁止运算元素;
//可非asii怎么办?{'value':"中文是合法的啊"}
//还有Eaeflnr-u   Eefnrtu可以理解  sa是什么呢?
            text.replace(/"(\\.|[^"\\])*"/g, ''))) &&//去掉字符串
          eval('(' + text + ')');
      } catch (e) {
        return false;
      }
    }


true
false
null
E(e)

不过这个版本貌似很老了,这个正则其实很偷懒,还是看json2.js那个好。
   
0 请登录后投票
时间:2008-05-07
bfnrtu 《--- 这又是什么组合呢?
   
0 请登录后投票
时间:2008-05-07
Army 写道
bfnrtu 《--- 这又是什么组合呢?


看代码注释呀。
   
0 请登录后投票
论坛首页 AJAX版 GWT

跳转论坛:
JavaEye推荐
    快速回复 引用上一条消息 (Alt+S)