Connecting Tech Pros Worldwide Help | Site Map

Using eval to parse a JSON text

  #1  
Old June 9th, 2006, 03:55 AM
radykl@gmail.com
Guest
 
Posts: n/a
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.

  #2  
Old June 9th, 2006, 05:05 AM
RobG
Guest
 
Posts: n/a

re: Using eval to parse a JSON text



radykl@gmail.com wrote:[color=blue]
> 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?[/color]

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

  #3  
Old June 9th, 2006, 05:45 AM
Matt Kruse
Guest
 
Posts: n/a

re: Using eval to parse a JSON text


radykl@gmail.com wrote:[color=blue]
> var json = "{a: 'abc', b: 'def'}";
> var obj1 = eval("(" + json + ")"); //ok![/color]

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


Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
concat multiple objects with JSON Andrew Poulos answers 1 December 10th, 2007 06:25 AM
Is Eval Evil for Ajax Responses Larry answers 24 December 1st, 2005 09:25 PM
JSON and the cyclical data structures... Luke Matuszewski answers 20 November 24th, 2005 08:35 PM
Sanitizing untrusted code for eval() Jim Washington answers 9 August 23rd, 2005 04:05 PM