Home > Web Front-end > JS Tutorial > body text

Methods and precautions for converting js strings into json objects

yulia
Release: 2018-09-14 14:31:10
Original
2252 people have browsed it

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; 
}
Copy after login

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; 
}
Copy after login

3, use the global JSON object, as follows:

function strToJson(str){ 
return JSON.parse(str); 
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template