First way:
Use js function eval();
testJson=eval(testJson); is the wrong conversion method.
The correct conversion method requires adding (): testJson = eval("(" testJson ")");
eval() is very fast, but it can compile and execute any javaScript program, so there will be security issues. Using eval(). The source must be trustworthy. Need to use a more secure json parser. If the server does not strictly encode the json or if the input is not strictly validated, it is possible to provide invalid json or contain dangerous scripts, execute the script in eval(), and release malicious code.
js code:
function ConvertToJsonForJs() {
//var testJson = "{ name: 'Xiaoqiang', age: 16 }"; (Supported)
//var testJson = "{ 'name': 'Xiaoqiang', 'age': 16 }"; (Supported)
var testJson = '{ "name": "Xiaoqiang", "age": 16 }';
//testJson=eval(testJson);//Wrong conversion method
testJson = eval("(" testJson ")");
alert(testJson.name);
}
The second method uses the jquery.parseJSON() method, which has higher requirements on the format of json and must comply with the json format
jquery.parseJSON()
js:code
function ConvertToJsonForJq() {
var testJson = '{ "name": "Xiaoqiang", "age": 16 }';
// Don’t know
//'{ name: "Xiaoqiang", age: 16 }' (name is not wrapped in double quotes)
//"{ 'name': "Xiaoqiang", 'age': 16 }" (name uses single quotes)
testJson = $.parseJSON(testJson);
alert(testJson.name);
}