zoukankan      html  css  js  c++  java
  • 在javascript中Json字符串的解析

    上代码:

     1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     2 <html xmlns="http://www.w3.org/1999/xhtml">
     3 <head runat="server">
     4     <title></title>
     5     <script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
     6     <script type="text/javascript">
     7         $(function () {
     8             var json = "{name:'成吉思汗',age:'90',content:'蒙古族'}";
     9             var obj01 = new Function("return" + json)();
    10             $(".div").append('new Function("return" + json)()' + "<br/>");
    11             $(".div").append(obj01.name + "<br/>");
    12             $(".div").append(obj01.age + "<br/>");
    13             $(".div").append(obj01.content + "<hr/>");
    14 
    15             var obj03 = eval("(" + json + ")")
    16             $(".div").append(' eval("(" + json + ")")' + "<br/>");
    17             $(".div").append(obj03.name + "<br/>");
    18             $(".div").append(obj03.age + "<br/>");
    19             $(".div").append(obj03.content + "<hr/>");
    20         });
    21         
    22 
    23     </script>
    24 </head>
    25 <body>
    26     <form id="form1">
    27     <div class="div">
    28     </div>
    29     </form>
    30 </body>
    31 </html>

    代码中展示了两种使用js解析json数据的方式。一种是使用new function方式转换。另一种用的是eval方式。

    在eval解析是切记:要在将json字符串前后加上"(",")"两个字符。是json字符包括在括号中。这样才能正常解析json字符。

    最后上图看结果:

    OK,大功告成,解析json成功!

  • 相关阅读:
    1442. Count Triplets That Can Form Two Arrays of Equal XOR
    1441. Build an Array With Stack Operations
    312. Burst Balloons
    367. Valid Perfect Square
    307. Range Sum Query
    1232. Check If It Is a Straight Line
    993. Cousins in Binary Tree
    1436. Destination City
    476. Number Complement
    383. Ransom Note
  • 原文地址:https://www.cnblogs.com/js-net/p/aspnet.html
Copyright © 2011-2022 走看看