Rojakcoder
Of Linux, Programming, and Singaporean Ramblings

JSON Object With Trailing Comma

Sat, Nov 14, 2009 1:11AM +0800

As any respectable JavaScript developer will know, JSON has become the de facto method of holding objects and passing arguments, even using it as a name-spacing mechanism.

Being the conscientious (and careless) programmer that I am, in my e-learning application that I’m developing at the moment, where I’m heavily using JSON, I made a conscious choice to always leave a comma at the end of the last member-value pair like so:

return { func1: function() { return “function1”; }, func2: function() { return “function2”; }, }

(Of course this is a simple example. In my actual code, the JSON object is several hundred lines long.)

This way, I’ll always be reminded that a comma is needed in between my function definitions, and it also acts as a way to identify the closing brace.

Sounds like a good idea right? Wrong. Turns out, it completely broke in IE7. The variable that is returning this JSON object was declared “undefined” in IE7, though the script worked fine in both Chrome and Firefox – even IE8.

Well, after some investigation, it appears that leaving a trailing comma in JSON is a wrong notation. The reason why the script worked in Chrome and FIrefox is that they treat this wrong notation as a warning, and continues to parse the object as though the comma isn’t there, whereas IE7 treats the trailing comma as an error and halts the interpretation of the object. Lo and behold, removing the comma brought peace, joy and laughter to IE7 world – while remaining sane in Chrome and Firefox.

return {
    func1: function() {
        return "function1";
    },
    func2: function() {
        return "function2";
    }
}

So lesson to learn here is: trailing commas are bad in JSON.

comments powered by Disqus