Javascript eval

I’ve seen a strange thing today. Mind you, things are strange just because we don’t understand them.

I was doing an eval on a JSON object:

someStr = “{ \”property\”:\”value\”};
obj = eval(someStr);

Firefox’ Javascript engine threw an exception at this point: Syntax error: invalid label. What the heck?

I looked it up online and found the solution on a blog. Replace the eval expression with:

obj = eval(“(” + someStr + “)”);

This looks weird and unexpected. In Python you can easily do an eval(someStr) and that returns a dictionary. No problem. So why the brackets in Javascript?

I started looking up the answer, but everyone was just saying that the brackets are there to work around an ambiguity in Javascript language. But what?!?

And then I found the first clue in MSDN:

Note The extra parentheses are used make eval unconditionally treat the source input like an expression. This is especially important for objects. If you try to call eval with a string containing JSON text that defines an object, such as the string “{}” (meaning an empty object), then it simply returns undefined as the parsed result. The parentheses force the JavaScript parser to see the top-level curly braces as the literal notation for an Object instance rather than, say, curly braces defining a statement block. Incidentally, the same problem does not occur if the top-level item is an array, as in eval(“[1,2,3]”). For sake of uniformity, however, JSON text should always be surrounded with parentheses prior to calling eval so that there is no ambiguity about how to interpret the source.

So, if you don’t add brackets, the Javascript engine things that the curly braces indicate a bunch of code, as in:

var a = 10;

as opposed to a JSON object. In other words, the brackets forces an expression, rather than code. And that’s because:

( { var a = 10; } )

is invalid in Javascript, whereas surrounding an expression in brackets is OK.


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: