Eval, JSON and curly braces.

October 10, 2006

Filed under: Script — Andrew @ 3:41 pm

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 and I’ll try to explain it using plain words:

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.

1 Comment

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.