JSON JS module for Firefox 3.0/3.5 API compatibility

I've written a JSON module to wrap the incompatible Firefox 3.0 and 3.5 JSON APIs, presenting the 3.5 API on both versions of Firefox, which is useful for extensions that support them both. Import this module to parse and stringify JSON in both 3.0 and 3.5 without having to check the host application's version each time.

Note: don't import this into the global namespace! If you do, you'll hork native Firefox 3.0 code that expects the 3.0 API. Instead, import it into your own object like this:

let MyExtension = {
JSON: null,
Components.utils.import("chrome://myextension/modules/JSON.js", MyExtension);
// Now MyExtension.JSON is an object implementing the Firefox 3.5 JSON API.

The module also works in Thunderbird 3.0, which uses Firefox 3.5's API (although there's no need to use it for an extension that only supports Thunderbird 3.0). I use it in Personas, which supports both Firefox 3.0 and 3.5 as well as Thunderbird 3.0.

The Firefox 3.5 JSON API is documented in the Mozilla Developer Center article Using JSON in Firefox. This JSON module is documented on Mozilla Labs' JS Modules wiki page.


Anonymous said...

Bonus points for checking against the Toolkit version instead of Firefox's (JSON.jsm shipped with all Gecko 1.9.0 applications). ;-)

Myk said...

Anonymous: you got it! The latest version of the module exports the Gecko 1.9.1 API on all Gecko 1.9.0 applications (as identified by nsIXULAppInfo::platformVersion).

Eric Shepherd said...

I've added a mention of this to the JSON article on MDC: https://developer.mozilla.org/en/JSON#JSON_via_JavaScript_module_for_Gecko_1.9_and_1.9.1