JSON (JavaScript Object Notation) is a simple data format, which is lighter than xml. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.
JSON rules are simple: the object is an unordered set of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs.
Let's first look at a DNS instance.
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> parse json objects using eval functions </title>
</Head>
<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>
</Html>
Notes for using eval () to parse strings in JSON format
Notes for parsing strings in JSON format using eval ()
When using the javascript built-in eval function to convert a string in json format to a JS object, you need to use a pair of "()" to enclose the string first.
For example:
Convert var strTest = "{id:" cnlei ", url:" http://www.jb51.net "}"; to JS object
Correct syntax:
Var objTEST = eval ("(" + strTEST + ")");
Incorrect syntax:
Var objTEST = eval (strTEST );
Complete Test code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
Var strTEST = "{id:" cnlei ", url:" http://www.jb51.net "}";
Var objTEST = eval ("(" + strTEST + ")"); // write the statement correctly
// Var objTEST = eval (strTEST); // Error writing method
Alert (objTEST. id + "n" + objTEST. url );
// -->
</Script>