To convert a string to a JSON object the method of the basic knowledge

Source: Internet
Author: User
Tags eval

JSON is a lightweight data interchange format that is easy to use. Easy for people to read and write. It is also easy to machine parse and generate. For details, please see: http://www.json.org/.

Many times we need to assemble a string as a JSON object, first combining the string and then converting to a JSON object, as in the following example:

Copy Code code as follows:

<script type= "Text/javascript" >
<!--
var a=50,b= "xxx";
var arr= ' {id: ' +a+ ', Name: ' +b+ '};
-->
</script>

Combined into a string arr, the next step is to convert to an object, and soon we will think of using the Eval method, but if this conversion will be wrong, today I try to do so, how to convert to a JSON object? Depressed for a long time, and then in the JSON website provided by the Json.js file found a solution, the following methods:

Add parentheses at both ends of the string and then eval is OK. The test code is as follows:

Copy Code code as follows:

<script type= "Text/javascript" >
<!--
var a=50,b= "xxx";
var arr= ' {id: ' +a+ ', Name: ' +b+ '};
Arr=eval (' (' +arr+ ') ')
alert (arr.name);
-->
</script>

The above code will pop up after "xxx", the description has been successfully converted to JSON object, a seemingly simple problem, but still depressed for a half-day to solve, or to the blog to deepen the impression, but also hope to help meet the problem of friends to relieve the frustration.

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.