Instance one,
In JS, the JSON-formatted string is converted to a JSON object, and the key code
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>
|
Example 2
Using the new function form
The code is as follows |
Copy Code |
function Strtojson (str) { var json = (new Function ("return" + str)) (); return JSON; } |
Example 3, using the relevant Json2 plug-in example
code is as follows |
copy code |
<script src=" ... /jquery/jquery-1.5.2.min.js "type=" Text/javascript "></SCRIPT> <script src=". /json2.js "type=" Text/javascript ></script> var a = ' {' name ' : "Tom", "Sex": "Male", "Age": "a"; //String used to compose JSON; alert ("string used to compose JSON:" "+a+" ""); var b = Json2.parse (a); //convert string A to JSON format B var c = json2.stringify (a); Converts JSON format B to string C alert ("Converted string:" "+c+" ""); |