native JSON support (window.JSON)

I have seen references to some browsers natively supporting JSON parsing/serialization of objects safely and efficiently via the window.JSON Object, but details are hard to come by. Can anyone point in the right direction? What are the methods this Object exposes? What browsers is it supported under?


All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically, JSON.parse(str) will parse the JSON string in str and return an object, and JSON.stringify(obj) will return the JSON representation of the object obj .

More details on the MDN article.


jQuery-1.7.1.js - 555行...

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





rvalidchars = /^[],:{}s]*$/,

rvalidescape = /(?:["/bfnrt]|u[0-9a-fA-F]{4})/g,

rvalidtokens = /"[^"nr]*"|true|false|null|-?d+(?:.d*)?(?:[eE][+-]?d+)?/g,

rvalidbraces = /(?:^|:|,)(?:s*[)+/g,

The advantage of using json2.js is that it will only install a parser if the browser does not already have one. You can maintain compatibility with older browsers, but use the native JSON parser (which is more secure and faster) if it is available.

Browsers with Native JSON:

  • IE8+
  • Firefox 3.1+
  • Safari 4.0.3+
  • Opera 10.5+
  • G.

    链接地址: http://www.djcxy.com/p/5426.html

    上一篇: 检查一个值是否是JavaScript中的一个对象

    下一篇: 本地JSON支持(window.JSON)