This article mainly introduces 2 methods of String (string) to JSON in JavaScript, two methods are using the JS function eval () and, using the Jquery.parsejson () method, the need for friends can refer to the
The first way:
Use the JS function eval ();
Testjson=eval (Testjson); Is the wrong way to convert.
The correct conversion method needs to be added (): Testjson = eval ("+ Testjson +"));
Eval () is very fast, but he can compile and execute any JavaScript program, so there are security issues. The eval () is used. The source must be trustworthy. You need to use a more secure JSON parser. If the server is not rigidly encoded in JSON or if the input is not rigorously validated, it is possible to provide invalid JSON or contain a dangerous script, execute the script in eval (), and release the malicious code.
JS Code:
The code is as follows:
function Converttojsonforjs () {
var Testjson = "{name: ' Cockroach ', age:16}";(support)
var Testjson = "{' name ': ' Cockroach ', ' Age ':}";(support)
var Testjson = ' {' name ': ' Cockroach ', ' age ': 16} ';
Testjson=eval (Testjson);//Wrong way of conversion
Testjson = eval ("+ Testjson +"));
alert (testjson.name);
}
The second way to use the Jquery.parsejson () method is to have a high format for JSON and must conform to the JSON format
Jquery.parsejson ()
JS: Code
The code is as follows:
function Converttojsonforjq () {
var Testjson = ' {' name ': ' Cockroach ', ' age ': 16} ';
I don't know
' {name: ' Cockroach ', age:16} ' (name is not wrapped with double quotes)
' {' name ': ' Cockroach ', ' age ': ' (name uses single quotes)
Testjson = $.parsejson (Testjson);
alert (testjson.name);
}