Javascript常用json操作

json 与 javascript 数据类型的转换:

view source
print ?
01 functionshowJSON()
02 {
03    varuser =
04    {
05        "username":"andy",
06        "age":20,
07        "info": {"tel":"123456","cellphone":"98765"},
08        "address":
09            [
10                {"city":"beijing","postcode":"222333"},
11                {"city":"newyork","postcode":"555666"}
12            ]
13    }        
14
15    alert(user.username);
16    alert(user.age);
17    alert(user.info.cellphone);
18    alert(user.address[0].city);
19    alert(user.address[0].postcode);
20    user.username ="Tom";
21    alert(user.username);        
22
23 }  

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

view source
print ?
1 //使用eval函数将字符串转化成json对象
2   functionmyEval()
3   {
4   varstr ='{ "name": "Violet", "occupation": "character" }';
5   varobj = eval('('+ str +')');          
6
7   alert(obj.toJSONString());
8   }   

或用json.js

view source
print ?
1 //使用 json.js 中的parseJSON方法
2   functionmyEval2() {
3   varstr ='{ "name": "Violet", "occupation": "character" }';
4   varobj = str.parseJSON();
5   alert(obj.toJSONString());    

将 json 对象转换为字符串 :

view source
print ?
01 functionshowCar() {
02    varcarr =newCar("Dodge","Coronet R/T", 1968,"yellow");
03    alert(carr.toJSONString());
04 }        
05
06 functionCar(make, model, year, color)       {
07     this.make  =  make;
08     this.model  =  model;
09     this.year  =  year;
10     this.color  =  color;
11 }     

view source
print ?
01 functiontest()
02  {
03        varmyJSONtext =
04        {
05            "bindings":
06            [
07                {"ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*"},
08                {"ircEvent":"PRIVMSG","method":"deleteURI","regex":"^delete.*"},
09                {"ircEvent":"PRIVMSG","method":"randomURI","regex":"^random.*"}
10            ]
11        };
12        varmyObject = eval(myJSONtext);
13        alert("对象长度:"+myObject.bindings.length);
14        for(vari=0;i<myObject.bindings.length;i++){
15            alert(myObject.bindings[i].method);
16        }
17  }   

你可能感兴趣的:(JavaScript,json操作)