JSON to object official text:
Address: http://www.json.org/js.html
To convert a JSON text into an object and you can use the eval () function. eval () invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler would correctly parse the text and produce an object structure. The text must is wrapped in parens to avoid tripping on a ambiguity in JavaScript ' s syntax.
var myObject = eval (' (' + myjsontext + ') ');
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 is a security issue. When using eval (). The source must be trustworthy. You need to use a more secure JSON parser. In the case where the server is not strictly encoded in JSON or if the input is not rigorously validated, it is possible to provide invalid JSON or a dangerous script, execute the script in eval (), and release the malicious code.
JS Code:
function Converttojsonforjs () { //var Testjson = "{name: ' Xiao Qiang ', age:16}";(support) // var Testjson = "{' name ': ' Xiao Qiang ', ' age ': 16}"; (support) var testjson = ' {' name ': "Xiao Qiang", "Age": +}' ; // Testjson=eval (Testjson);//Wrong conversion mode Testjson = eval ("(" + Testjson + ")"); alert (testjson.name); }
The second method uses the Jquery.parsejson () method to format the JSON more highly, and must conform to the JSON format
Jquery.parsejson ()
JS Code:
function converttojsonforjq () { var testjson = ' {' name ': "Xiao Qiang", "Age": +}' ; // Don't know // ' {name: ' Xiao Qiang ', age:16} ' (name is not wrapped with double quotes) // "{' Name ':" Xiao Qiang ", ' Age ': +}" (name using single quotes) Testjson = $.parsejson (testjson); alert (testjson.name); }
JSON to string, json to object