Browser-native JSON support (window.JSON)

2018-12-31 20:48发布

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?

5条回答
笑指拈花
2楼-- · 2018-12-31 21:04

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,
查看更多
荒废的爱情
3楼-- · 2018-12-31 21:13

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.

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 21:13

[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.

查看更多
梦该遗忘
5楼-- · 2018-12-31 21:19

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+.

查看更多
低头抚发
6楼-- · 2018-12-31 21:23

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.

查看更多
登录 后发表回答