jQuery.parseJSON vs JSON.parse

后端 未结 7 1299
感情败类
感情败类 2020-11-27 06:29

jQuery.parseJSON and JSON.parse are two functions that perform the same task. If the jQuery library is already loaded, would using jQuery.parseJSON be better th

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 07:08

    Here is an extract from jQuery 1.9.1:

    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 );
    },
    

    As you can see, jQuery will use the native JSON.parse method if it is available, and otherwise it will try to evaluate the data with new Function, which is kind of like eval.

    So yes, you should definitely use jQuery.parseJSON.

提交回复
热议问题