Why does JavaScript's eval need parentheses to eval JSON data?

Tomo picture Tomo · Jun 8, 2009 · Viewed 12.4k times · Source

I've learned (the hard way) that I need to add parentheses around JSON data, like this:

stuff = eval('(' + data_from_the_wire + ')');
// where data_from_the_wire was, for example {"text": "hello"}

(In Firefox 3, at least).

What's the reason behind this? I hate writing code without understanding what´s behind the hood.

Answer

karim79 picture karim79 · Jun 8, 2009

eval accepts a sequence of Javascript statements. The Javascript parser interprets the ‘{’ token, occuring within a statement as the start of a block and not the start of an object literal.

When you enclose your literal into parentheses like this: ({ data_from_the_wire }) you are switching the Javascript parser into expression parsing mode. The token ‘{’ inside an expression means the start of an object literal declaration and not a block, and thus Javascript accepts it as an object literal.