浏览器本机 JSON 支持(window.JSON)

我见过一些浏览器的引用,它们本身支持通过 window.JSON对象安全有效地对对象进行 JSON 解析/序列化,但是很难获得详细信息。有人能指出正确的方向吗?这个 Object 公开的方法是什么?它支持哪些浏览器?

69609 次浏览

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.

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.

[extending musicfreak comment]

If you are using jQuery, use parseJSON

var obj = jQuery.parseJSON(data)

Internally it checks if browser supports .JSON.parse, and (if available) calls native window.JSON.parse.

If not, does parse itself.

jQuery-1.7.1.js - 555 line...

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 = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,


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

For the benefit of anyone who runs into this thread - for an up-to-date, definitive list of browsers that support the JSON object look here.. A brief generic answer - pretty much all browsers that really matter in the year 2013+.