jQuery has many kick-ass javascript utilities. Among these is a method (jQuery.getJSON()
) that parses JSON that you grab from a remote source and gives it back to you as a JSON object. Excellent!
Surprisingly though, jQuery (as of 1.3, to my knowledge anyway) does not make any functions available to allow you to securely parse a simple text string into JSON. Not sure why this is so, especially since they must do it behind the scenes for the getJSON()
method, but so be it.
I needed this functionality, though, so I could pass some data from one of my templates to a jQuery function I’m working on.
Fortunately, even though jQuery doesn’t have built-in functionality for this, it was relatively trivial to wrap the open source JSON parsing and stringifying library published by JSON.org in an easy-to-use jQuery plugin.
So that’s what I did. I changed nothing of the JSON parsing library implementation published by JSON.org; I just wrapped two jQuery methods around it, as follows:
;(function($) { if (!this.JSON) { var JSON = {}; } /* ... implementation of parse() and stringify() here ... */ $.toJSON = function(text, reviver) { if (typeof reviver == "undefined") { reviver = null; } return JSON.parse(text, reviver); }; $.jSONToString = function(value, replacer, space) { if (typeof replacer == "undefined") { replacer = null; } if (typeof space == "undefined") { space = null; } return JSON.stringify(value, replacer, space); }; })(jQuery);
Pretty convenient. Now I can securely parse and decode JSON to my heart’s content.
Here’s the source code of the full jQuery JSON plugin, if you’re interested. Note that I have not extensively tested the plugin, but since I did not actually touch any part of the JSON parsing library it’s based on (save for creating a local scope for the JSON variable), I wouldn’t foresee any issues.
Here’s a bit more information about the library the plugin is based on.