


Detailed explanation of the method of converting string to json object_Basic knowledge
May 16, 2016 pm 05:11 PMJSON is a lightweight data exchange format that is easy to operate and use. Easy for humans to read and write. It is also easy for machines to parse and generate. For detailed introduction, please see: http://www.json.org/.
Many times we need to assemble strings into json objects. We must first assemble the strings and then convert them into json objects, as in the following example:
<script type="text/javascript">
<!--
var a=50,b=" xxx";
var arr="{id:" a ",name:'" b "'}";
//-->
</script>
is combined into a string arr. The next step is to convert it into an object. Soon we will think of using the eval method, but if we do this, an error will occur in the conversion. I tried this today. How to convert it into a json object? Woolen cloth? After being depressed for a long time, I found a solution in the json.js file provided by the json official website. The method is as follows:
Add parentheses at both ends of the string and then eval will be ok. The test code is as follows:
<script type="text/ javascript">
<!--
var a=50,b="xxx";
var arr="{id:" a ",name:'" b "'}";
arr=eval('(' arr ')')
alert(arr.name);
//-->
</script>
After the above code is executed, "xxx" will pop up, indicating that it has been successfully converted into a json object. It seems to be a very simple problem, but it still took me a long time to solve it. I still wrote it on the blog to deepen my impression. I also hope it can help others. Friends who have encountered this problem can get rid of their depression as soon as possible.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of the method of converting int type to string in PHP

How to determine whether a Golang string ends with a specified character

How to check if a string starts with a specific character in Golang?

How to repeat a string in python_python repeating string tutorial

How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP

PHP string manipulation: a practical way to effectively remove spaces

PHP String Matching Tips: Avoid Ambiguous Included Expressions

PHP techniques for deleting the last two characters of a string
