用户Email
您可以使用以下JSON形式来表示User对象:
{"UserID":11, "Name":"Truly", "Email":"zhuleipro◎hotmail.com"};
然后如果把这一字符串赋予一个JavaScript变量,那么就可以直接使用对象的任一属性了。
完整代码:
var User = {"UserID":11, "Name":"Truly", "Email":"zhuleipro◎hotmail.com"};
alert(User.Name);
实际使用时可能更复杂一点,比如我们为Name定义更详细的结构,使它具有FirstName和LastName:
{"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"}
完整代码:
var User = {"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"};
alert(User.Name.FirstName);
现在我们增加一个新的需求,我们某个页面需要一个用户列表,而不仅仅是一个单一的用户信息,那么这里就需要创建一个用户列表数组。
下面代码演示了使用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"}
]
完整代码:
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);
事实上除了使用"."引用属性外,我们还可以使用下面语句:
alert(UserList[0]["Name"]["FirstName"]); 或者 alert(UserList[0].Name["FirstName"]);
现在读者应该对JSON的使用有点认识了,归纳为以下几点: