JavaScript uses Eval to parse JSON points of attention

Source: Internet
Author: User

For a JSON-formatted string, you need to be aware of the parentheses when you use eval to convert a string to a JSON object. As shown below:

<script type= "Text/javascript" >
var data = ' {root:[{name: "1", Value: "0"},{name: "6101", Value: "Beijing"},{name: "6102", Value: "Tianjin"}]} ';
var dataobj_1 = eval (data);
var dataobj_2 = eval ("+ Data +"));
Console.info (dataobj_1);
Console.info (dataobj_2);
</script>

The results of this code are as follows:

The results of this code are as follows:

Figure 1: Code Run results

The results appear as above because the eval itself can parse and run the code in the string. Since JSON starts and ends in {}, it is treated as a block of statements in JS, so it is imperative to convert it to an expression without being treated as a block of statements. The purpose of parentheses is to force the function to convert an expression in parentheses to an object when it is processed instead of executing it as a statement.

It's easy to accept that this is a problem on the web, but it's worth noting.

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.