Wednesday, September 9, 2009

"Microsoft JScript compilation error: Expected ';'" when parsing JSON in Javascript

This is a nasty one that I struggled with a bit.

I had some code parsing a JSON string returned from a callback.
var layer = eval(jsonLayer);

This worked fine, until I changed the object that was serialized to and from JSON from a collection inheriting from System.Collections.Generic.List to a base object, with the collection as a property.

I suddenly started getting an error stating "Microsoft JScript compilation error: Expected ';'"

Changing the code to:
var layer = eval("(" + jsonLayer + ")");
solved the problem. ( eval("var layer = " + json); will also work)

A discussion of the problem can be found here.

It turns out that while my object was a collection, the generated JSON looked something like this:
[{a: 'abc', b: 'def'},{a: 'ghi', b: 'jkl'}]
The parser clearly understood this as a collection object being initiated.

When I changed the underlying object, the JSON changed to something like this:
{a: 'abc', b: 'def', c: [{d: 'ghi'},{d: 'jkl'}]}
The string now started with a curly bracket '{', instead of a square bracket '['.

When evaluating this string using eval(), this quite literally means the start of a new block statement, with stuff inside evaluated as a set of instructions, and hence the error. Putting the parenthesis around the string changes it's meaning to denote the contents of an expression, and it is then treated as an object initialiser.
Without the parenthesis, the statement occurs as a lefthand statement, but with it, it is a right hand statement.