JSON

JSON是Javascript对象标记法

JSON是一种轻量级的数据交换格式

JSON具有自我描述且易于理解

为什么使用JSON:因为JSON格式仅仅是文本,它能够轻松地在服务器浏览器之间传输,并用作任何编程语言的数据格式。

JavaScript提供内建函数把以JSON格式写的字符串转换为JavaScript对象:

JSON.parse()

因此,如果以JSON格式从服务器接收数据,那么可以像JavaScript对象一样使用它。

JSON语法规则

(1)数据在名称/值对中

(2)数据由逗号分割

(3)花括号容纳对象

(4)方括号容纳数组

"name":"mez"  //(1)

JSON名称需要双引号。而JavaScript名称不需要。

JSON格式几乎等同于JavaScript对象

在JSON中,键必须是字符串,由双引号包围

而在JavaScript中,键可以是字符串、数字或标识名称:

name:"mez"      //javascript

JSON值

在JSON中,值必须是以下数据类型之一:

字符串、数字、对象(JSON对象)、数组、布尔、null

而在JavaScript中,不仅包括上述类型,还包括:

函数、日期、undefined

在JSON中,字符串必须由双引号编写。

而在JavaScript中,字符串可以由双引号和单引号编写。

JSON使用JavaScript语法

因为JSON语法由JavaScript对象标记法衍生而来,所以很少需要其他额外的软件来处理JavaScript中的JSON。

通过JavaScript,可以创建对象并向其分配数据:

var person =  { name : "mez", age : 12, city : "Shanghai" };

可以使用person.name访问JavaScript对象,或者person["name"]

可以直接对JavaScript进行赋值来修改数据

person.name = "Steve Jobs";
//或
person["name"] = "Steve Jobs";

JSON文件的文件类型是“.json”

JSON文本的MIME类型是“application/json”

JSON.parse()

JSON的常规用途是同web服务器进行数据传输。

在从web服务器接收数据时,数据永远是字符串

通过JSON.parse()解析数据,这些数据会成为JavaScript对象。

<!--
 * @Author: RealRoad1083425287@qq.com
 * @Date: 2023-03-16 16:19:58
 * @LastEditors: Mei
 * @LastEditTime: 2023-03-20 20:23:12
 * @FilePath: \vscode\请求方式\测试.html
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="mypost">post1</button>

    <script>
        // mypost.onclick=function(){
        //     var xhr=new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload=function(){
        //         if(xhr.status===200){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        //     xhr.send(`username=lisi&password=4578`)
        // }
        // mypost.onclick = function(){
        //     var xhr = new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload = function(){
        //         if(/^2\d{2}$/.test(xhr.status)){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }
        //     //提交 信息
        //     //post name=kerwin&age=100
        //     //post {"name":"kerwin"}

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //name=kerwin&age=100
        //     xhr.send(`username=shanzhen&password=456`)
            // xhr.setRequestHeader("Content-Type","application/json") //name=kerwin&age=100
            // xhr.send(JSON.stringify({
            //     username:"zhuang",
            //     password:"789"
            // }))
        // }
        var obj=JSON.parse(`{"name":"mez","age":17}`)
        console.log(obj.name)
        console.log(obj["age"])
    </script>
</body>
</html>

JavaScript学习笔记(9.6)_json

 

<!--
 * @Author: RealRoad1083425287@qq.com
 * @Date: 2023-03-16 16:19:58
 * @LastEditors: Mei
 * @LastEditTime: 2023-03-20 20:28:19
 * @FilePath: \vscode\请求方式\测试.html
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="mypost">post1</button>
    <p id="demo"></p>
    <script>
        // mypost.onclick=function(){
        //     var xhr=new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload=function(){
        //         if(xhr.status===200){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        //     xhr.send(`username=lisi&password=4578`)
        // }
        // mypost.onclick = function(){
        //     var xhr = new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload = function(){
        //         if(/^2\d{2}$/.test(xhr.status)){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }
        //     //提交 信息
        //     //post name=kerwin&age=100
        //     //post {"name":"kerwin"}

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //name=kerwin&age=100
        //     xhr.send(`username=shanzhen&password=456`)
        // xhr.setRequestHeader("Content-Type","application/json") //name=kerwin&age=100
        // xhr.send(JSON.stringify({
        //     username:"zhuang",
        //     password:"789"
        // }))
        // }
        // var obj=JSON.parse(`{"name":"mez","age":17}`)
        // console.log(obj.name)
        // console.log(obj["age"])
        var text = '{"employees":[' +
            '{"firstName":"Bill","lastName":"Gates" },' +
            '{"firstName":"Steve","lastName":"Jobs" },' +
            '{"firstName":"Elon","lastName":"Musk" }]}';

        obj = JSON.parse(text);
        document.getElementById("demo").innerHTML =
            obj.employees[1].firstName + " " + obj.employees[1].lastName;
    </script>
</body>

</html>

JavaScript学习笔记(9.6)_json_02

 来自服务器的JSON

可以使用Ajax请求从服务器请求JSON。

只要服务器的响应是用JSON格式编写的,就可以将字符串解析成JavaScript对象

<!--
 * @Author: RealRoad1083425287@qq.com
 * @Date: 2023-03-16 16:19:58
 * @LastEditors: Mei
 * @LastEditTime: 2023-03-20 20:34:28
 * @FilePath: \vscode\请求方式\测试.html
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="mypost">post1</button>
    <p id="demo"></p>
    <script>
        // mypost.onclick=function(){
        //     var xhr=new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload=function(){
        //         if(xhr.status===200){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        //     xhr.send(`username=lisi&password=4578`)
        // }
        // mypost.onclick = function(){
        //     var xhr = new XMLHttpRequest()
        //     xhr.open("POST","http://localhost:3000/users")

        //     xhr.onload = function(){
        //         if(/^2\d{2}$/.test(xhr.status)){
        //             console.log(JSON.parse(xhr.responseText))
        //         }
        //     }
        //     //提交 信息
        //     //post name=kerwin&age=100
        //     //post {"name":"kerwin"}

        //     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //name=kerwin&age=100
        //     xhr.send(`username=shanzhen&password=456`)
        // xhr.setRequestHeader("Content-Type","application/json") //name=kerwin&age=100
        // xhr.send(JSON.stringify({
        //     username:"zhuang",
        //     password:"789"
        // }))
        // }
        // var obj=JSON.parse(`{"name":"mez","age":17}`)
        // console.log(obj.name)
        // console.log(obj["age"])
        // var text = '{"employees":[' +
        //     '{"firstName":"Bill","lastName":"Gates" },' +
        //     '{"firstName":"Steve","lastName":"Jobs" },' +
        //     '{"firstName":"Elon","lastName":"Musk" }]}';

        // obj = JSON.parse(text);
        // document.getElementById("demo").innerHTML =
        //     obj.employees[1].firstName + " " + obj.employees[1].lastName;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                myObj = JSON.parse(this.responseText);
                document.getElementById("demo").innerHTML = myObj.name;
            }
        };
        xmlhttp.open("GET", "json_demo.txt", true);
        xmlhttp.send();
        // console.log()
    </script>
</body>

</html>

JavaScript学习笔记(9.6)_javascript_03

JavaScript学习笔记(9.6)_学习_04

 

 作为JSON数组

在对衍生数组的JSON使用JSON.parse()后,此方法将返回JavaScript数组,而不是JavaScript对象

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()  {
    if (this.readyState == 4 && this.status == 200) {
        myArr =  JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML  = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();




//json_demo_array.txt内容
[ "porsche", "BMW", "Volvo", "Audi" ]