Browser-native JSON support (window.JSON)
Asked Answered
N

5

95

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?

Nix answered 21/5, 2009 at 3:33 Comment(1)
See When can I use JSON parsing? for info on browsers with native support for the JSON object.Satin
E
112

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.

Exsert answered 21/5, 2009 at 3:40 Comment(8)
I know the support is not widespread, but using this method should be a lot faster and safer than eval()ing a string, so I want to use it where it's available. Any idea on support from other browsers?Nix
I didn't say don't use it, I said don't count on it. Definitely check to see if it's available (at this point only IE8 and the few Fx Beta users) and use it if so, but I'm just saying that you shouldn't assume the browser supports it. As of now, those two are the only browsers that support it, and WebKit is working on it right now, so it'll probably be in Google Chrome and Safari sometime soon.Exsert
Oh, and on a side note, NEVER eval() JSON strings. Instead, use one of the many JSON parsing libraries available.Exsert
Of the "many" libraries available, are they any preferred? Is the one at json.org/json2.js generally the most used? I noticed references to it in jQuery 1.4 source.Firsthand
@colbeerhey: Yeah, that's the one I see most often. You could also steal jQuery's.Exsert
code.google.com/chrome/extensions/faq.html#faq-dev-07 - Google Chrome supports natively. I don't know how long is it.Dzoba
For reference, when you say "NEVER eval() ..." and then mention that json2 is the popularly supported library, it's worth noting that it does use eval, but it attempts to validate the string using regex first. This is faster than validating and parsing the string, though there are parsers that don't validate with comparable performance. json2.js is still probably the best choice, if only for its pervasiveness.Tiebout
@TheXenocide: Good point, but its author probably spent a good chunk of time on that validation code, so I say never eval() JSON strings because you will be reinventing the wheel and you will likely get it wrong.Exsert
L
30

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,
Lanceolate answered 12/3, 2012 at 1:38 Comment(2)
Nice. Good argument to use jQuery.Seismo
More like an argument to look inside jQuery =)Introject
H
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.

Hearts answered 5/8, 2011 at 14:35 Comment(0)
D
10

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

Decided answered 20/10, 2011 at 23:23 Comment(0)
F
9

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

Frequentative answered 18/11, 2013 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.