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数据是由键值对构成的
- 键用引号(单双都行)引起来,也可以不使用引号
- 值的取值类型:
- 数字(整数或浮点数)
- 字符串(在双引号)
- 逻辑值(true 或 false)
- 数组(在方括号中) {"person":[{},{}]}
- 对象(在花括号中) {"address":{"province":"北京"......}}
- null
- 数据由逗号分隔:多个键值对由逗号分隔
- 花括号保存对象:使用{}定义 json 格式
- 方括号保存数组:[]
//定义基本格式
var person = {"name": "张三", "age": 23, "gender": true};
//2.嵌套格式 {}-->[]
var persons = {
"persons": [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
]
};
//2.嵌套格式 []-->{}
var ps = [
{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
];
2、获取数据:
- json对象.键名
- json对象["键名"]
- 数组对象[索引]
- 遍历
//定义基本格式
var person = {"name": "张三", "age": 23, "gender": true};
//获取name的值
//var name = person.name;
var name = person["name"];
//alert(name);
//2.嵌套格式 {}-->[]
var persons = {
"persons": [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
]
};
//获取王五
var name1 = persons.persons[2].name;
//alert(name1)
//2.嵌套格式 []-->{}
var ps = [
{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
];
//获取李四
var name2 = ps[1].name;
alert(name2);
var person = {"name": "张三", "age": 23, "gender": true};
var ps = [
{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
];
//获取person对象中所有的键和值
//for in 循环
/*for(var key in person){
//alert(key + ":" + person.key);//这样获取不到值,相当于person."name"
alert(key + " : " + person[key]);//自带了引号
}*/
//获取ps中的所有值
for(var i = 0; i < ps.length; i++){
for (var key in ps[i]){
alert(key + " : " + ps[i][key]);
}
}