JSON: JavaScript Object Notation JavaScript 对象表示法。
由于现在很多在服务器获取数据,很多都涉及json数据格式,因此学习json非常有必要。
* 语法格式:
1. {键1:值1,键2:值2...} -- json格式
var person = {"name":"zhangsan","age":23,"gender":"male"};
2.[值1,值2,值3...] -- 数组格式
var persons = [ {"name":"zhangsan","age":23,"gender":"male"}, {"name":"zhangsan","age":23,"gender":"male"}, {"name":"zhangsan","age":23,"gender":"male"}]
* 这两种基本格式可以混合使用,形成复杂的格式
* 注意:
* json的键是字符串。
* json的值可以使任意的类型
* 访问数据:
1.引用名称.键的名称: 如 person.name
还可以写为: 引用名称["键的名称"] 如 : person["name"]
2.数组可以使用角标获取元素
看一看它的时如何获取数据的:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title> <script type="text/javascript">
/* var person = {"name":"zhangsan","age":23,"gender":"male"}; //alert(person.name);
alert(person["name"]); */ //访问复杂格式
var persons = {
"persons":[
{"name":"zs","age":23,"gender":"male"},
{"name":"ls","age":24,"gender":"female"}, {"name":"ww","age":25,"gender":"male"}
]
} /*
1. persons.persons 获取persons键对应的数组
2.[0] 获取第一个元素 这个元素是json类型的对象
3. .name 根据name键 获取json中对应的值
*/
//alert(persons.persons[0].name); var persons = [
{"name":"zs","age":23,"gender":"male"},
{"name":"ls","age":24,"gender":"female"},
{"name":"ww","age":25,"gender":"male"}
] /*
1.获取数组中的第二个json对象 persons[1]
2. .age */
alert(persons[1].age); </script> </head>
<body> </body>
</html>