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.