Salient Solutions

wrasslin ones and nones for fun and profit - Sky Sanders' Blog
posts - 96, comments - 70, trackbacks - 0

Saturday, August 21, 2010

Firefox native JSON stringify STILL buggy. Here's a patch

Almost a year ago, during my WCF Date<-->JSON Date adventure, I discovered a bug in the Firefox native JSON implementation where in the stringify replacer does not behave properly.

 

I and several other people bugged it on bugzilla, but it still hasn't been fixed.

 

So, you can not trust Firefox native JSON stringify.

 

What is the solution?

If you are using JSON, you are (or should be) loading json2.js regardless and letting it defer to native implementations when they are present. In the case of Firefox, this leaves you flat, so here is a feature detecting prefix for json2.js.

 

 

(function() {

    // ff STILL has buggy native stringify
    // https://bugzilla.mozilla.org/show_bug.cgi?id=548462
    // we will use feature detection to determine if we need
    // to replace the native stringify

    if (typeof (JSON) == 'undefined') {
        JSON = {};
    };

    if (typeof JSON.stringify == 'function') {

        var s = JSON.stringify({ date: new Date(2009, 1, 1, 10, 10) }, function(key, value) {
            if (key == "date") {
                return String("SERIALIZED");
            };
            return value;
        });

        var sobj = JSON.parse(s);
        if (sobj.date !== "SERIALIZED") {
            JSON.stringify = {};
        };
    };
})();

// insert json2.js here

(function() {
    // ensure bug patched
    if (typeof JSON.stringify == 'function') {

        var s = JSON.stringify({ date: new Date(2009, 1, 1, 10, 10) }, function(key, value) {
            if (key == "date") {
                return String("SERIALIZED");
            };
            return value;
        });

        var sobj = JSON.parse(s);
        if (sobj.date !== "SERIALIZED") {
            throw new Error("JSON STILL BROKEN");
        };
    };
})();

posted @ Saturday, August 21, 2010 3:08 AM | Feedback (0) |

Powered by: