javascript常用json操作

json 与 javascript 数据类型的转换:


  function showJSON()     
   {         
      var user =          
      {          
          "username":"andy",         
          "age":20,         
          "info": { "tel": "123456", "cellphone": "98765"},         
          "address":         
              [         
                  {"city":"beijing","postcode":"222333"},         
                  {"city":"newyork","postcode":"555666"}         
              ]         
      }         
               
      alert(user.username);         
      alert(user.age);         
      alert(user.info.cellphone);         
      alert(user.address[0].city);         
      alert(user.address[0].postcode);       
      user.username = "Tom";         
      alert(user.username);         
         
  }   

将字符串转换为json 对象/数组:


//使用eval函数将字符串转化成json对象            
   function myEval()      
   {            
   var str = '{ "name": "Violet", "occupation": "character" }';            
   var obj = eval('(' + str + ')');           
       
   alert(obj.toJSONString());            
   }    

或用json.js


//使用 json.js 中的parseJSON方法     
   function myEval2() {            
   var str = '{ "name": "Violet", "occupation": "character" }';            
   var obj = str.parseJSON();            
   alert(obj.toJSONString());     

将 json 对象转换为字符串 :


 function showCar() {         
     var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");         
     alert(carr.toJSONString());         
 }         
         
 function Car(make, model, year, color)       {         
      this.make  =  make;         
      this.model  =  model;         
      this.year  =  year;         
      this.color  =  color;         
 }      


function test()     
  {      
        var myJSONtext =      
        {        
            "bindings":      
            [        
                {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},        
                {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},        
                {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}        
            ]        
        };        
        var myObject = eval(myJSONtext);        
        alert("对象长度:"+myObject.bindings.length);        
        for(var i=0;i<myObject.bindings.length;i++){        
            alert(myObject.bindings[i].method);        
        }       
  }    

发表评论

电子邮件地址不会被公开。 必填项已用*标注