Using eval to parse a JSON text

Discussion in 'Javascript' started by radykl@gmail.com, Jun 9, 2006.

  1. Guest

    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, 2006
    #1
    1. Advertising

  2. RobG Guest

    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
    RobG, Jun 9, 2006
    #2
    1. Advertising

  3. Matt Kruse Guest

    Matt Kruse, Jun 9, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Florian Frank
    Replies:
    0
    Views:
    222
    Florian Frank
    Jun 30, 2009
  2. bizt
    Replies:
    1
    Views:
    106
    Thomas 'PointedEars' Lahn
    Jul 1, 2008
  3. sajuptpm
    Replies:
    2
    Views:
    311
    sajuptpm
    Dec 28, 2012
  4. Acácio Centeno
    Replies:
    1
    Views:
    237
    dieter
    Feb 15, 2013
  5. Bryan Britten
    Replies:
    9
    Views:
    253
    Bryan Britten
    May 28, 2013
Loading...

Share This Page