In work, we often need to convert JS strings into JSON objects. Next, we will introduce several methods to you. Convert JS strings to JSON objects. Convert to JSON, this tutorial has certain reference value, friends in need can refer to it.
1, eval method analysis, I am afraid this is the earliest analysis method. As follows:
function strToJson(str){ var json = eval('(' + str + ')'); return json; }
Remember not to forget the parentheses on both sides of str.
2, the new Function form is quite weird. As follows
unction strToJson(str){ var json = (new Function("return " + str))(); return json; }
3, use the global JSON object, as follows:
function strToJson(str){ return JSON.parse(str); }
Currently IE8(S)/Firefox3.5/Chrome4/Safari4/Opera10 has implemented this method.
Using JSON.parse must strictly abide by JSON specifications. For example, attributes need to be enclosed in quotation marks, as follows
ar str = '{name:"jack"}'; var obj = JSON.parse(str); // --> parse error
If the name is not enclosed in quotation marks, all browsers using JSON.parse will throw Exception, parsing failed. The first two methods are fine.
Notes:
1. The string passed from the background to the foreground is just a string. You also need to convert the json string into a js object. You can pass The JSON.parse(jsonStr) method converts the background json string into the front-end json object.
2. You also need to pay attention to the spelling of the json string. The attributes and values are surrounded by double quotes. If you use single quotes, congratulations! If you fall into a trap, the front desk cannot parse it correctly.
3. Finally, it is important to mention that the quotation marks in the string in the Java backend require the use of the transfer character "\".
The above is the detailed content of Methods and precautions for converting js strings into json objects. For more information, please follow other related articles on the PHP Chinese website!