JSON的结构基于下面两点
这里假设我们需要创建一个User对象,并具有以下属性
您可以使用以下JSON形式来表示User对象:
然后如果把这一字符串赋予一个JavaScript变量,那么就可以直接使用对象的任一属性了。
完整代码:
实际使用时可能更复杂一点,比如我们为Name定义更详细的结构,使它具有FirstName和LastName:
{ " UserID " : 11 , " Name " :{ " FirstName " : " Truly " , " LastName " : " Zhu " }, " Email " : " zhuleipro◎hotmail.com " }
完整代码:
< script > var User = { " UserID " : 11 , " Name " :{ " FirstName " : " Truly " , " LastName " : " Zhu " }, " Email " : " zhuleipro◎hotmail.com " };
alert(User.Name.FirstName);
</ script >
现在我们增加一个新的需求,我们某个页面需要一个用户列表,而不仅仅是一个单一的用户信息,那么这里就需要创建一个用户列表数组。
下面代码演示了使用JSON形式定义这个用户列表:
[
{ " UserID " : 11 , " Name " :{ " FirstName " : " Truly " , " LastName " : " Zhu " }, " Email " : " zhuleipro◎hotmail.com " },
{ " UserID " : 12 , " Name " :{ " FirstName " : " Jeffrey " , " LastName " : " Richter " }, " Email " : " xxx◎xxx.com " },
{ " UserID " : 13 , " Name " :{ " FirstName " : " Scott " , " LastName " : " Gu " }, " Email " : " xxx2◎xxx2.com " }
]
完整代码:
< script >
var UserList = [
{ " UserID " : 11 , " Name " :{ " FirstName " : " Truly " , " LastName " : " Zhu " }, " Email " : " zhuleipro◎hotmail.com " },
{ " UserID " : 12 , " Name " :{ " FirstName " : " Jeffrey " , " LastName " : " Richter " }, " Email " : " xxx◎xxx.com " },
{ " UserID " : 13 , " Name " :{ " FirstName " : " Scott " , " LastName " : " Gu " }, " Email " : " xxx2◎xxx2.com " }
];
alert(UserList[ 0 ].Name.FirstName);
</ script >
事实上除了使用"."引用属性外,我们还可以使用下面语句:
alert(UserList[ 0 ][ " Name " ][ " FirstName " ]); 或者 alert(UserList[ 0 ].Name[ " FirstName " ]);
现在读者应该对JSON的使用有点认识了,归纳为以下几点:
小节:
本文通过一个实例演示,初步了解了JSON 的强大用途。可以归结如下:
参考资料:
http://www.json.org/
http://www.cnblogs.com/Truly/archive/2006/12/31/608896.html
http://www.json.org/json-zh.html