javascript使用json

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Untitled Document</title>
  <script type="text/javascript" src="json.js"></script>
  <script type="text/javascript">
      function test() {
              var jsontext = '{"man":{"weight":"75kg", "age":"24"},"ar":["1", "2", "3", "4"]}';
     //解析json
     var aman = eval("("+jsontext+")");
     //取出json中的信息
     alert(aman.man.weight);
   }
   
   function showJSON() {
     var user = {
        "username":"andy",
      "age":"24",
      "info":{"tel":"123456", "cellphone":"98756"},
      "address":[
         {"city":"beijing", "postcode":"222233"},
      {"city":"newwork", "postcode":"444455"},
      ]
    
     }
     user.username = "tom";
     alert("username="+user.username);
     alert("age="+user.age);
     alert("info="+user.info.cellphone);
     alert("address第一个地址 =" + user.address[0].city); 
     alert("address第二个地址 =" + user.address[1].city);    
   }
   
   function showCar() {
    var carr = new Car("Donge", "Coronet R/T", 123, "yellow");
    alert(carr.toJSONString());
   }

           function Car(make, model, year, color) {   
              this.make  =  make;   
              this.model  =  model;   
              this.year  =  year;   
              this.color  =  color;   
           }
    
           function myEval() {   
              var str = '{ "name": "Violet", "occupation": "character" }';   
              var obj = eval('(' + str + ')');   
              alert(obj.toJSONString());   
           } 
    
           function myEval2() {   
              var str = '{ "name": "Violet2", "occupation": "character2" }';   
              var obj = str.parseJSON();   
              alert(obj.toJSONString());   
           } 
          
     function toJsonString() {
      var continents = new Array();
            continents.push("Europe");
   continents.push("Asia");
   continents.push("Australia");
   continents.push("Antarctica");
   continents.push("North America");
   continents.push("South America");
   continents.push("Africa");
   alert("The JSON representation of the continents array is: " +continents.toJSONString());   
     }  
  </script>
 </head>
 <body>
  <input type="button" value="测试JSON" οnclick="test();"><br />
  
  <input type="button" value="测试JSON2" οnclick="showJSON();"><br />
  
  <input type="button" value="showCar" οnclick="showCar();"><br />
  
  <input type="button" value="Eval转换" οnclick="myEval();"><br />
  
  <input type="button" value="JSON转换" οnclick="myEval2();"><br />

  <input type="button" value="toJsonString" οnclick="toJsonString();"><br />
 </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值