JSON概念和JSON语法的定义与值的获取

JSON概念

概念: JavaScript Object Notation  JavaScript 对象标记法

var p = {"name":"张三","age":23,"gender":"男"};

 

json现在多用于存储和交换文本信息的语法

进行数据的传输

JSON比XML更小、更快、更易解析。

 

JSON语法

语法_定义

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>
        //定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        // alert(person);

        //嵌套格式  {}————>  []
        var persons = {
            "persons":[
                {"name":"张三","age":23,"gender":true},
                {"name":"李四","age":29,"gender":true},
                {"name":"王五","age":24,"gender":false}
            ]
        };
        //alert(persons);

        //嵌套格式   []————> {}
        var ps = [
            {"name":"张三","age":23,"gender":true},
            {"name":"李四","age":29,"gender":true},
            {"name":"王五","age":24,"gender":false}
            ];
        alert(ps);

    </script>
</head>
<body>

</body>
</html>

语法_获取定义的数据

1.json对象.键名

2.json对象["键名"]

3.数组对象[索引]

.

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        //定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        // alert(person);

        //获取name的值
        //var name = person.name;
        var name = person["name"];
        //alert(name);

        //遍历
        //for in循环
        /*
        for (var key in person){
            alert(key+":"+person[key]);
        }
        */


        //嵌套格式  {}————>  []
        var persons = {
            "persons":[
                {"name":"张三","age":23,"gender":true},
                {"name":"李四","age":29,"gender":true},
                {"name":"王五","age":24,"gender":false}
            ]
        };
        //alert(persons);
                  //对象名称  键名称
        var name1 = persons.persons[2].name;
        //alert(name1);



        //嵌套格式   []————> {}
        var ps = [
            {"name":"张三","age":23,"gender":true},
            {"name":"李四","age":29,"gender":true},
            {"name":"王五","age":24,"gender":false}
        ];
        //alert(ps);
        //alert(ps[1].name);
      
        //获取ps中全部的值  双重for进行遍历
        for (let i = 0; i <ps.length; i++) {
            var p = ps[i];
            for (var key in p){
                alert(key+":"+p[key]);
            }
        }

    </script>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

 

posted @ 2022-08-20 15:56  魔光领域  阅读(41)  评论(0编辑  收藏  举报