JSON (JavaScript Object notation) is a simple data format that is lighter than XML. JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.
The rule of JSON is simple: an object is an unordered set of ' name/value pairs '. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" followed by a ":" (colon); "' Name/value ' pairs" (comma) separated
Let's take a look at an analytic example
The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" > <meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/> <title>eval function parsing JSON object </title> <body> <script type= "Text/javascript" > var json=eval ({sitename: ' Dreamdu ', Sitedate:new Date (1980, 12, 17, 12, 0, 0)}); document.write (Json.sitename); document.write ("<br/>"); document.write (json.sitedate); </script> </body>
|
Eval () issues to be noted in parsing JSON format strings
Issues to be aware of using eval () to parse a JSON format string
When you convert a JSON-formatted string to a JS object using the JavaScript built-in eval function, you need to wrap the string in a pair of "()".
For example:
will Var Strtest= ' {id: ' cnlei ', url: ' http://www.111cn.net '} '; Convert to JS object
Correct:
var objtest=eval ("(" +strtest+) ");
Error spelling:
var objtest=eval (strtest);
code is as follows |
copy code |
Complete test code: <script type= "Text/javascript" <!-- var strtest= "{ID: cnlei", url: "http:// Www.111cn.net "}"; var objtest=eval ("+strtest+");//correct writing //var objtest=eval (strtest); Error spelling alert (objtest.id+ "n" +objtest.url); //--> </script> |