JSON-语法-值的获取
获取数据:
1. json对象.键名
2. json对象[ " 键名 " ]
3. 数组对象[ 索引 ]
4. 遍历
JSON值的获取
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> //定义基本格式 var person = {"name":"张三",age: 23,'gender':true}; //获取name的值 // let name = person.name; var name = person["name"]; //alert(name) //alert(person) //2.嵌套格式 {}--->[] var persons={"persons":[ {"name":"张三","age":18,"gender":true}, {"name":"李四","age":18,"gender":true}, {"name":"王五","age":18,"gender":false} ] }; //获取王五值 let name1 = persons.persons[2].name; // alert(name1) //2.嵌套格式 []--->{} var ps = [ {"name":"张三","age":18,"gender":true}, {"name":"李四","age":18,"gender":true}, {"name":"王五","age":18,"gender":false} ]; //获取李四值 alert(ps[1].name) </script> </head> <body> </body> </html>
JSON数据语法遍历
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> //定义基本格式 var person = {"name":"张三",age: 23,'gender':true}; var ps = [ {"name":"张三","age":18,"gender":true}, {"name":"李四","age":18,"gender":true}, {"name":"王五","age":18,"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>
标签:name,person,gender,age,语法,获取,JSON,18,var From: https://www.cnblogs.com/xuche/p/17113838.html