Using eval to parse a JSON text

R

radykl

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.
 
R

RobG

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.
 
M

Matt Kruse

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top