JSON的概念
概念: JavaScript Object Notation JacaScript对象表示法
json现在多用于存储和交换文本信息的语法
进行数据的传输
JSON 比 XML 更小 更快 ,更易解析
语法定义:
1.基本规则
数据在名称/值对中:json数据是由键值对构成的
键用引号(单双都行)引起来,也可以不使用引号
值得取值类型:
1. 数字(整数或浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true 或 false)
4. 数组(在方括号中) {"persons":[{},{}]}
5. 对象(在花括号中) {"address":{"province":"陕西"....}}
6. null
数据由逗号分隔:多个键值对由逗号分隔
花括号容纳对象:使用 { } 定义json格式
方括号容纳数组:[ ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { //1.定义基本格式 let person = {"name":"张三",age:23,'gender':true}; //alert(person); //2.嵌套格式 {}---> [] let persons = { "persons":[ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":21,"gender":false}, {"name":"王五","age":22,"gender":true} ] }; //alert(persons) //3.嵌套格式 []---> {} let ps = [ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":21,"gender":false}, {"name":"王五","age":25,"gender":true} ]; } </script> </head> <body> </body> </html>
2.获取数据
1.json对象.键名
2.json对象[ " 键名 " ]
3.数组对象[ 索引 ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { //1.定义基本格式 let person = {"name":"张三",age:23,'gender':true}; //获取name的值 //let name = person.name; let name = person["name"]; // alert(name); //alert(person); //2.嵌套格式 {}---> [] let persons = { "persons":[ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":21,"gender":false}, {"name":"王五","age":22,"gender":true} ] }; //获取王五值 let name1 = persons.persons[2].name; //alert(name1); //alert(persons) //3.嵌套格式 []---> {} let ps = [ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":21,"gender":false}, {"name":"王五","age":25,"gender":true} ]; //alert(ps); //获取李四值 alert(ps[1].name); } </script> </head> <body> </body> </html>
JSON遍历数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { //1.定义基本格式 let person = {"name":"张三",age:23,'gender':true}; // 数组格式 let ps = [ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":21,"gender":false}, {"name":"王五","age":25,"gender":true} ]; //获取person对象中所有的键和值 //for in 循环 // for (let key in person){ // alert(key + ":" + person[key]); // } //获取ps中的所有值 for (let i = 0; i < ps.length; i++) { let p = ps[i]; for (let key in p) { alert(key + ":" + p[key]); } } } </script> </head> <body> </body> </html>
标签:定义,gender,age,语法,person,JSON,let,true,name From: https://www.cnblogs.com/qihaokuan/p/17100757.html