This article mainly introduces two methods for converting string (string) to json in JavaScript, namely using js function eval () and jquery. parseJSON () method. For more information, see
Method 1:
Use the js function eval ();
TestJson = eval (testJson); is the incorrect 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. When using eval (). The source must be trustworthy. Use a safer json parser. If the server is not strictly encoded in json or if the input is not strictly verified, it is possible to provide invalid json or contain dangerous scripts and execute the script in eval, release malicious code.
Js code:
The code is as follows:
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); // The conversion method is incorrect.
TestJson = eval ("(" + testJson + ")");
Alert (testJson. name );
}
The second method is to use the jquery. parseJSON () method, which requires a high requirement on the json format and must comply with the json format.
Jquery. parseJSON ()
Js: code
The code is as follows:
Function ConvertToJsonForJq (){
Var testJson = '{"name": "Xiaoqiang", "age": 16 }';
// Unknown
// '{Name: "Xiaoqiang", age: 16}' (name is not enclosed in double quotation marks)
// "{'Name':" Xiaoqiang ", 'age': 16}" (single quotes are used for name)
TestJson = $. parseJSON (testJson );
Alert (testJson. name );
}