469,626 Members | 1,581 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,626 developers. It's quick & easy.

Using eval to parse a JSON text

Can anyone explain me why you need to add open and close parenthesis to
a JSON text in order to use eval() to parse it?
For example:

var json = "{a: 'abc', b: 'def'}";
var obj1 = eval("(" + json + ")"); //ok!
var obj2 = eval(json); //syntax error!

why are parenthesis necessary?

Thanks!

/Andres.

Jun 9 '06 #1
2 59659

ra****@gmail.com wrote:
Can anyone explain me why you need to add open and close parenthesis to
a JSON text in order to use eval() to parse it?
For example:

var json = "{a: 'abc', b: 'def'}";
var obj1 = eval("(" + json + ")"); //ok!
var obj2 = eval(json); //syntax error!

why are parenthesis necessary?


For the same reson as:

{a: 'abc', b: 'def'};

causes an error but:

( {a: 'abc', b: 'def'} );

does not.

When encountered on the left hand side, the punctuator '{' defines the
start of a block statement, like if{... or while{... etc. The stuff
inside the block is evaluated as if it were a series of statements, so
the script engine attempts to evaluate:

a: 'abc', b: 'def'

and barfs (understandably).

By enclosing the expression in () it is evaluated as if it were the
right hand side of an expression, in which case {} is treated as an
object initialiser. So what you must pass to eval is:

( { /* property names & values */ } )

as a literal string to force it to treat the {} as an object
initialiser.
--
Rob

Jun 9 '06 #2
ra****@gmail.com wrote:
var json = "{a: 'abc', b: 'def'}";
var obj1 = eval("(" + json + ")"); //ok!


Rob already stated the reason. But I'm wondering why you wouldn't use
eval("var obj1="+json);
instead?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jun 9 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Patrick De Ridder | last post: by
1 post views Thread by Joel Byrd | last post: by
8 posts views Thread by abhishek | last post: by
7 posts views Thread by Darko | last post: by
5 posts views Thread by Smiley | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.