概念 JavaScript Object Notation :JavaScript对象表示法
JSON现在对于存储和交换信息的语法
进行数据的传输
JSON 比 XML 更小、更快、更易解析
作用(早期) 在Java中:
1 2 3 4 Person p = new person(); p.setName("张三" ); p.setAge(23 ); p.setGender("男" );
在JavaScript中
1 var p ={"name" :"张三" ,"age" :"23" ,"gender" :"男" }
语法 基本规则 1. 数据在名称/值对中:JSON数据是由键值对构成的
* 键用引号(单双都行)引起来,也可以不使用引号
* 值的取值类型:
1. 数字(整数和浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true和false)
4. 数组(在方括号中){"person":[{1},{2}]}
5. 对象(在华括号中){"address":{"provice":"陕西..."}}
6. null
2. 数据由逗号分隔:多个键值对由逗号分隔
3. 花括号保存对象:使用{}定义JSON格式
4.
5. 方括号保存数组:[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 var person = {"name" :"张三" ,"age" :"23" ,"gender" :"true" } var person = {"person" :[ {"name" :"张三" ,"age" :"23" ,"gender" :"true" }, {"name" :"李四" ,"age" :"24" ,"gender" :"true" }, {"name" :"王五" ,"age" :"21" ,"gender" :"false" }]} var ps = [ {"name" :"张三" ,"age" :"23" ,"gender" :"true" }, {"name" :"李四" ,"age" :"24" ,"gender" :"true" }, {"name" :"王五" ,"age" :"21" ,"gender" :"false" }]
获取数据 1. JSON对象: 对象.键名
2. JSON对象["键名"]
3. 数组对象[索引]
代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 var person = {"name" :"张三" ,"age" :"23" ,"gender" :"true" }var name = person["name" ];console .log(name)var persons = {"person" :[ {"name" :"张三" ,"age" :"23" ,"gender" :"true" }, {"name" :"李四" ,"age" :"24" ,"gender" :"true" }, {"name" :"王五" ,"age" :"21" ,"gender" :"false" }]} var name2 = persons.person[2 ].name;console .log(name2); var ps = [ {"name" :"张三" ,"age" :"23" ,"gender" :"true" }, {"name" :"李四" ,"age" :"24" ,"gender" :"true" }, {"name" :"王五" ,"age" :"21" ,"gender" :"false" }] console .log(ps[1 ].name) for (let key in ps[1 ]){ console .log(key+":" +ps[1 ][key]); console .log(key+":" +ps[1 ].key); } for (let i = 0 ; i <= ps.length; i++) { let p = ps[i]; for (let key in p){ console .log(key+"=" +p[key]); } }
取数据结果
<
轻量级数据交换格式-JSON解析器
JavaEE核心技术之Listener监听器
>