Js USES eval to parse json instances to share with considerations

  • 2020-03-30 01:24:07
  • OfStack

JSON (JavaScript Object Notation) is a simple data format that is lighter than XML. JSON is native to JavaScript, which means you don't need any special apis or toolkits to process JSON data in JavaScript.
The rule for JSON is simple: an object is an unordered collection of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with"} "(right parenthesis). Each name is followed by: (colon); "Name/value" pairs are separated by ", "(comma)

Let's start with an example of parsing

<!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 analysis json object </title>  
  <script type="text/javascript">
  var json=eval("({sitename:'dreamdu',sitedate:new Date(1980, 12, 17, 12, 0, 0)})");
  document.write("<br />"); 

Eval () parses json-formatted strings
Parse json-formatted strings with eval()
When converting a json-formatted string into a JS object using javascript's built-in eval function, you need to wrap the string in a pair of "()" s.
Such as:
The var strTest = {" id: "cnlei", url: / / www.jb51.net "} "; Convert to a JS object
Correct writing:
StrTEST var objTEST = eval (" (" + + ") ");
Error writing:
Var objTEST = eval (strTEST);

Complete test code:

<script type="text/javascript">
    var strTEST="{id:"cnlei", url:"//www.jb51.net"}";
    var objTEST=eval("("+strTEST+")"); //Correct term
    //var objTEST=eval(strTEST); // Error writing 

Related articles: