Why use eval ("({A: 'B'})") to convert a string to a JSON object?

Source: Internet
Author: User
For the same reson:

{A: 'abc', B: 'def '};

Causes an error:

({A: 'abc', B: 'def '});

Does not.

When encountered on the left hand side, the punctuator '{'defines
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
Right hand side of an expression, in which case {} is treated as
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.