Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Using eval to parse a JSON text

Reply
Thread Tools

Using eval to parse a JSON text

 
 
radykl@gmail.com
Guest
Posts: n/a
 
      06-09-2006
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.

 
Reply With Quote
 
 
 
 
RobG
Guest
Posts: n/a
 
      06-09-2006

http://www.velocityreviews.com/forums/(E-Mail Removed) 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

 
Reply With Quote
 
 
 
 
Matt Kruse
Guest
Posts: n/a
 
      06-09-2006
(E-Mail Removed) 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Lib to generate XML/JSON[P] output from a DTD/XSD/JSON Schema/etc Acácio Centeno Python 1 02-15-2013 07:34 AM
I am facing an issue while decoding json string using json.loads sajuptpm Python 2 12-28-2012 07:16 AM
[ANN] Security Fix json-1.1.7 for json_pure and json gems Florian Frank Ruby 0 06-30-2009 05:18 PM
Using AJAX/JSON and performance issues with eval() bizt Javascript 1 07-01-2008 12:02 PM
"JSON for ASP" at json.org Tuğrul Topuz ASP General 1 06-27-2008 11:37 PM



Advertisments