首页 > 其他分享 >JSON_语法_值得获取

JSON_语法_值得获取

时间:2022-08-21 10:56:30浏览次数:55  
标签:name person gender age 语法 获取 JSON var true

JSON_语法_值得获取

  • json对象.键名
  • json对象["键名"]
  • 数据对象[索引]

获取值:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //定义基本格式
        var person = {"name": "张三", "age": 17, "gender": true};

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


        //嵌套格式:{} ---> []
        var persons = {
            "persons": [{
                "name": "张三", "age": 17, "gender": true}, {
                "name": "李四", "age": 20, "gender": false}, {
                "name": "王五", "age": 21, "gender": true}],
        };

        // var name = persons.persons[2].name;
        // alert(name);


        //嵌套格式[]-->{}
        var ps = [{
            "name": "张三", "age": 17, "gender": true}, {
            "name": "李四", "age": 20, "gender": false}, {
            "name": "王五", "age": 21, "gender": true}];

        alert(ps[1].name);
    </script>
</head>
<body>

</body>
</html>

遍历:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var person = {"name": "张三", "age": 17, "gender": true};

        //获取persons对象中的所有键和值
        // for in循环
        for (let personKey in person) {
            //这样的方式获取不行。因为相当于person."name"
            // alert(personsKey + ":" + person.key);
            // alert(personKey + ":" + person[personKey]);
        }

        //嵌套格式[]-->{}
        var ps = [{
            "name": "张三", "age": 17, "gender": true}, {
            "name": "李四", "age": 20, "gender": false}, {
            "name": "王五", "age": 21, "gender": true}];
        //获取ps中的所有值
        for (var i = 0; i < ps.length ; i++) {
            var p = ps[i];
            for (let pKey in p) {
                document.writeln(pKey + ":" + p[pKey]);
            }
            document.write("<br>")
        }


    </script>
</head>
<body>

</body>
</html>

标签:name,person,gender,age,语法,获取,JSON,var,true
From: https://www.cnblogs.com/ailhy/p/16609610.html

相关文章