My question is: is it safe to use native JSON parser nowadays, or should I worry that some browsers may not support it?
If I have to include the json script, how should I do it? My script is wrapped in an anonymous function. Should the json script be included there? Outside the scope of this anonymous function?
It would still be a good idea to include it, as IE6/7 donβt have native JSON parsing (http://caniuse.com/#feat=json)
If you use the json2.js it will only add the JSON methods if they do not already exist, for example:
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
If you use an anonymous function closure around your script, you can pass in the JSON object as an parameter to the closure, the only pre-requisite is of course that the JSON script is executed before you use it
( function ( JSON ) {
//safe to use JSON
} )( JSON );
And for example, if you use a library like jQuery, you could pass it into your closure as well.
( function ( JSON, $ ) {
//safe to use JSON and $ as a jQuery alias
} )( JSON, jQuery );
While it is certainly possible to include the JSON library in your closure, it would probably not be feasible to do this with a library like jQuery