Json基本语法
1. 基本规则
数据在名称/值对中:json数据是由键值对构成的
键用引号(单双都行)引起来,也可以不使用引号
值得取值类型:
1. 数字(整数或浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true 或 false)
4. 数组(在方括号中) {“persons”:[{},{}]}
5. 对象(在花括号中) {“address”:{“province”:“陕西”…}}
6. null
数据由逗号分隔:多个键值对由逗号分隔
花括号保存对象:使用{}定义json 格式
方括号保存数组:[]
2. 获取数据
json对象.键名
json对象[“键名”]
数组对象[索引]
遍历
<script>
//1.定义基本格式
var person = {"name":"张三","age":23,"gender":true};
//获取name的值
var name = person.name;
alert(name);
var name1 = person["name"];
alert(name1);
//2.嵌套格式
var persons = {"persons":[
{"name":"张三","age":23,"gender":true},
{"name":"李四","age":43,"gender":false},
{"name":"王五","age":56,"gender":true}
]};
var name2 = persons.persons[2].name;
alert(name2);
//3.嵌套格式
var ps = [
{"name":"张三","age":23,"gender":true},
{"name":"李四","age":43,"gender":false},
{"name":"王五","age":56,"gender":true}
];
alert(ps[1].name);
</script>
3.json遍历
<script>
var person = {"name":"张三","age":23,"gender":true};
var ps = [
{"name":"张三","age":23,"gender":true},
{"name":"李四","age":43,"gender":false},
{"name":"王五","age":56,"gender":true}
];
//获取person对象中所有的键和值
for(var key in person){
//alert(key);
alert(key+":"+person[key]);
}
//获取ps中的所有值
for(i=0;i<ps.length;i++){
var p = ps[i];
for(var key in p){
alert(key+":"+p[key]);
}
}
</script>