Sunday, March 15, 2009

Eval, JSON and curly braces.

Say, you have JSON data (object literal) stored as a string somewhere:

  "{ one:1, two:2 }"

and you want to parse (convert) this string into scripting object.

Obvious solution for this would be to write something like this:

  var dataStr = "{ one:1, two:2 }";
var data = eval( dataStr );

Looks nice and simple but will not work. To make it work you need to wrap your string in ( ) brackets:

  var dataStr = "(" + "{ one:1, two:2 }" + ")";
var data = eval( dataStr );

Reason is simple:

eval accepts sequence of statements of JavaScript and at this level JavaScript parser
interprets ‘{’ token as a start of a block and not a start of an object literal.

When you will enclose your literal into () brackets like this: ({ one:1, two:2 })
you are switching JavaScript parser into expression parsing mode. Token ‘{’ inside expression means start of object literal declaration so JavaScript will accept it.

http://www.terrainformatica.com/?p=14

No comments: