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:
Copy Code code as follows:
function Converttojsonforjs () {
var Testjson = "{name: ' Cockroach ', age:16}";(support)
var Testjson = "{' name ': ' Cockroach ', ' age ': 16}"; (supported)
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
Copy Code code 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);
}