jQuery静态方法parseJSON方法使用和源码分析

来源:互联网 发布:linux mysql下载64位 编辑:程序博客网 时间:2024/06/05 20:30

该方法接受一个JSON字符串,返回解析后的对象。

传入一个畸形的JSON字符串会抛出一个异常。比如下面的都是畸形的JSON字符串:

  • {test: 1} ( test 没有包围双引号)
  • {'test': 1} (使用了单引号而不是双引号)

另外,如果你什么都不传入,或者一个空字符串、null或undefined,parseJSON都会返回 null 。

源码分析:

parseJSON: function( data ) {   if ( typeof data !== "string" || !data ) {       return null; }

首先对参数进行过滤,如果data不是字符串或者可以转换为false则接着返回null

// Make sure leading/trailing whitespace is removed (IE can't handle it)data = jQuery.trim( data );

在解析之前首先要清理掉首尾空格,否则在ie中会出现解析失败

// Attempt to parse using the native JSON parser firstif ( window.JSON && window.JSON.parse ) {      return window.JSON.parse( data ); }

因为ie8以上和w3c标准的浏览器提供了解析的方法,所以如果浏览器支持优先采用

复制代码
// Make sure the incoming data is actual JSON// Logic borrowed from http://json.org/json2.jsif ( rvalidchars.test( data.replace( rvalidescape, "@" )     .replace( rvalidtokens, "]" )     .replace( rvalidbraces, "")) ) {        return ( new Function( "return " + data ) )();}
复制代码

对于不支持JSON对象的浏览器有首先确保传入的字符串是合法的,通过几个正则式来进行完善,最后返回解析后的结果

// JSON RegExprvalidchars = /^[\],:{}\s]*$/,rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

这几个正则在jQuery构造函数中创建

new Function( "return " + data )

Function构造函数接受字符串参数,然后把这些字符串参数在函数内部解析,下面举例:

var json='[{"success":"0"}]';console.log(new Function('var data='+json));/* (function() {var data=[{"success":"0"}]})*/      

这样直接给函数示例一个自执行加return就会返回解析后的结果

jQuery.error( "Invalid JSON: " + data );

如果执行到这里说明json无法解析,调用error方法报错,最后附上完整连续源码:

复制代码
    parseJSON: function( data ) {        if ( typeof data !== "string" || !data ) {            return null;        }        // Make sure leading/trailing whitespace is removed (IE can't handle it)        data = jQuery.trim( data );        // Attempt to parse using the native JSON parser first        if ( window.JSON && window.JSON.parse ) {            return window.JSON.parse( data );        }        // Make sure the incoming data is actual JSON        // Logic borrowed from http://json.org/json2.js        if ( rvalidchars.test( data.replace( rvalidescape, "@" )            .replace( rvalidtokens, "]" )            .replace( rvalidbraces, "")) ) {            return ( new Function( "return " + data ) )();        }        jQuery.error( "Invalid JSON: " + data );    },
复制代码

 

0 0
原创粉丝点击