Transforming the JSON data returned by the server side

Source: Internet
Author: User
Tags eval json

Talk about the use of the built-in function eval () for JS.

It was originally used to convert a JSON-formatted string sent from the background into a JSON object. It turned out to be really powerful, much more than that, but today it's just about it. If you want to know more about the next W3school can be referred to.

To get to the point:

Java code

<script>
var json='{"id":1}';
alert(json.id);
</script>

If you look carefully, you can see that the above Code pop-up dialog box is not to show the ID. The reason is that JSON is just a string object, not a true JSON object, and notice the outermost two single quotes.

Java code

<script>
var json={"id":1};//去掉单引号
alert(json.id);
</script>

With the single quotation mark removed, the ID is displayed successfully. The JSON at this point is a JSON object.

The JSON data that is now returned from the server is a single quote, as in the first example, and cannot be used directly. What about it?

The answer is the eval () function mentioned at the beginning.

Java code

<script>
var json='{"id":1}';
var jsonObj=eval("("+json+")");//注意这一行
alert(jsonObj.id);
</script>

The ID is displayed successfully.

Note two key points:

1. If JSON is just a single object, rather than an array of objects, as shown in the previous example, you cannot write Eval directly (JSON).

2. Eval ("+json+") cannot be written as an eval (' ("+json+ ') '), otherwise the ID will not be displayed.

Let me cite one more example:

Java code

<script>
var json='[{"id":1}]';
var jsonObj=eval(json);
alert(jsonObj[0].id);
</script>

IDs can still be displayed successfully. Note The difference: JSON contains an array of objects, not a single object. But why this can be, and the previous example is not possible, I was confused, but also asked the master enlighten.

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.