JSON概念和语法定义
作者:互联网
JSON概念
概念:JavaScript Object Notation JavaScript对象表示法
- Person p=new Person();
- p.setName("张三“);
- p.setAge(23);
- p.setGender("男");
- var p = {"name":"张三","age":23,"gender":男};
- json现在多用于存储和交换文本信息的语法
- 进行数据的传递
- JSON比XML更小、更快,更易解析
JSON语法定义
基本规则
- 数据在名称/值对中:json数据是由键值对构成的
- 键用引号(单双都行)引起来,也可以不使用引号
- 值得取值类型:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true或false)
- 数组(在方括号中){”persons“:[{},{}]}
- 对象(在花括号中){”address":{"province":陕西....}}
- null
- 数据又逗号分隔:多个键值对由逗号分隔
- 花括号保存对象:使用{}定义json格式
- 方括号保存数组:[]
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Json数据语法</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义基本格式 var person = {"name": "张三", age: 23, 'gender': true}; //alert(person) //2.嵌套格式 var persons = { "persons": [{"name": "张三", "age": 23, 'gender': true}, {"name": "张三", "age": 23, 'gender': true}, {"name": "张三", "age": 23, 'gender': true}] }; alert(persons); //嵌套格式[]->{} var ps=[ [{"name": "张三", "age": 23, 'gender': true}, {"name": "张三", "age": 23, 'gender': true}, {"name": "张三", "age": 23, 'gender': true}] ]; alert(ps) </script> </head> <body> </body> </html>
运行结果
获取数据
单独获取数据
- json对象.键名
- json对象["键名"]
- 数组对象[索引]
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Json数据语法</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义基本格式 var person = {"name": "张三", age: 23, 'gender': true}; //获取name的值 var name=person["name"]; alert(name) //2.嵌套格式 var persons = { "persons": [{"name": "张三", "age": 23, 'gender': true}, {"name": "李四", "age": 23, 'gender': true}, {"name": "王五", "age": 23, 'gender': true}] }; //alert(persons); //获取王五的值 var name1 = persons.persons[2].name; alert(name1); //嵌套格式[]->{} var ps=[ {"name": "张三", "age": 23, 'gender': true}, {"name": "李四", "age": 23, 'gender': true}, {"name": "王五", "age": 23, 'gender': true} ]; //alert(ps) //获取李四的值 alert(ps[1].name); </script> </head> <body> </body> </html>
运行结果
遍历获取数据
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Json数据语法</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //1.定义基本格式 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){ //这样的方式获取不行。因为相当于 person."name" //alert(key + ":" + person.key); alert(key+":"+person[key]); } //获取ps中的所有值 for (var i = 0; i < ps.length; i++) { var p = ps[i]; for(var key in p){ alert(key+":"+p[key]); } } </script> </head> <body> </body> </html>
标签:定义,23,gender,age,语法,JSON,var,true,name 来源: https://www.cnblogs.com/aimz01/p/16609649.html