In JS, the JSON-formatted string is converted to a JSON object, and the key code
Example 1
The code is as follows |
Copy Code |
JSON = eval (' (' +str+ ') '); |
The method is as follows:
The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/> <title>json Application </title> <script type= "Text/javascript" > function Strtojson (str) { JSON = eval (' (' +str+ ') '); return JSON; } function Tojson (data) { JSON = eval (data); return JSON; } JSON data str = ' {id:1,title: Hello, friend ', Addtime: ' 2010-05-03 '} '; Strjson = Strtojson (str); data = {id:2,title: "Hello, haha", addtime: "2010-05-04"}; Json = Tojson (data); document.write (strjson.id+ "," +strjson.title+ "" +strjson.addtime+ "<br/>"); document.write (json.id+ "," +json.title+ "" +json.addtime+ "<br/>"); </script> <body> </body>
|
2,new function form, more bizarre Oh. As follows
The code is as follows |
Copy Code |
function Strtojson (str) { var json = (new Function ("return" + str)) (); return JSON; } |
3, use the global JSON object as follows:
The code is as follows |
Copy Code |
function Strtojson (str) { return Json.parse (str); } |
The following two conversion methods are recommended for personal use Oh, this relatively secure method, especially json.parse, converts strings to objects.