Js parses json instances using eval and shares precautions

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.