Saturday, November 16, 2013

Javascript JSON Trailing Comma and IE

Seems like Google Chrome and Firefox are both pretty tolerant when it comes to trailing commas in JSON. However IE can be really pissed off by those extra characters.

Two symptoms I typically see:

  • Syntax Error: IE will simply report a syntax error like this: SCRIPT1028: Expected identifier, string or number
JSON string that can cause above error message:

var x = {
    a: 1,
    b: 2,};

  • Undefined object: when the trailing comma is in an array declaration, IE will add a undefined object at the end of the array (Firefox, and Chrome does not do this). For example, for the code below, my test results are: IE -> 4, Firefox -> 3, Google Chrome -> 3

var x = [1, 2, 3,];
alert(x.length);

       This usually will cause unexpected error in the code down below, which may loop through the array and try to access the undefined last element.

It is the second kind of problem that causes the most headache. Because in the first case, IE will pinpoint line number so that we can fix the problem immediately. In the second case, you are likely to get an obscure error message from a code that is trying to access the undefined last object.

No comments: