jQuery.parseJSON vs JSON.parse

转载:http://stackoverflow.com/questions/10362277/jquery-parsejson-vs-json-parse

一、JavaScript函数JSON.parse

将 JavaScript 对象表示法 (JSON) 字符串转换为对象。

调用如下:

JSON.parse(text [, reviver])

一、jQuery函数jQuery.parseJSON($.parseJSON)

调用如下:

var jsonObj = $.parseJSON(jsonStr);

jQuery的parseJSON函数定义如下:

parseJSON: function( data ) {
    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    if ( data === null ) {
        return data;
    }

    if ( typeof data === "string" ) {

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

        if ( 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 );
},
View Code

posted on 2014-03-04 10:09  儿时精神  阅读(538)  评论(0编辑  收藏  举报

导航