1.概念
JavaScript Object Notation JavaScript对象表示法
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
var p={"name":"张三","age":23,"gender":"男"};
json现在多用于存储和交换文本信息的语法
进行数据的传输
JSON比xml更小,更快,更易解析
2.语法
(1)基本规则
①数据在名称/值对中:json数据是由键值对构成的
a.数字(整数或浮点数)
b.字符串(在双引号中)
c.逻辑值(true或false)
d.数组(在方括号中){“persons”:[{},{}]}
e.对象(在花括号中){“address”:{“province”:“陕西”…}}
f.null
②数据有逗号分隔:多个键值对由逗号分隔
③花括号保存对象:使用{}定义json格式
④方括号保存数组:[]
示例
<script>
//1,定义基本格式
var p = {"name":"战三",age:23,'gender':true};
//alert(person);
//2.嵌套格式{}->[]
var person = {"persons":[
{"name":"张三","age":23,"gender":true},
{"name":"李四","age":24,"gender":false},
{"name":"王五","age":25,"gender":true}]};
alert(person);
//3嵌套格式[]->{}
var ps = [{"name":"张三","age":23,"gender":true},
{"name":"李四","age":24,"gender":false},
{"name":"王五","age":25,"gender":true}];
</script>
(2)获取数据
a.json对象.键名
b.json对象[“键名”]
c.数组对象[索引]
示例
<script>
//1,定义基本格式
var p = {"name":"战三",age:23,'gender':true};
//获取name的值
//var name = p.name;
var name = p["name"];
alert(name)
//2.嵌套格式{}->[]
var person = {
"persons":[
{"name":"张三","age":23,"gender":true},
{"name":"李四","age":24,"gender":false},
{"name":"王五","age":25,"gender":true}
]};
//获取王五的值
var name1 = person.persons[2].name;
alert(name1)
//3嵌套格式[]->{}
var ps = [{"name":"张三","age":23,"gender":true},
{"name":"李四","age":24,"gender":false},
{"name":"王五","age":25,"gender":true}];
//获取李四的值
alert(ps[1].name);
</script>
3.遍历
示例
<script>
var p = {"name":"战三",age:23,'gender':true};
var ps = [{"name":"张三","age":23,"gender":true},
{"name":"李四","age":24,"gender":false},
{"name":"王五","age":25,"gender":true}];
//获取p对象中所有的键和值
//for in 循环
for(var key in p){
alert(key);
alert(key+":"+p[key]);
}
//获取ps中的所有值
for (var i = 0; i < ps.length; i++) {
var per = ps[i];
for (var key in per) {
alert(key+":"+per[key]);
}
}
</script>