Home >Web Front-end >JS Tutorial >JSON for JavaScript learning and understanding (summary sharing)

JSON for JavaScript learning and understanding (summary sharing)

WBOY
WBOYforward
2022-03-23 13:16:571855browse

This article brings you relevant knowledge about javascript, which mainly introduces related issues about JSON, including JSON objects, JSON arrays and JSON strings, etc. I hope it will be helpful to everyone helpful.

JSON for JavaScript learning and understanding (summary sharing)

Related recommendations: javascript tutorial

1. JSON object

Task description

Task for this level: Practice defining JSON objects in JavaScript.

The specific requirements are as follows:

  • Define a JSON object JSONObject, which has three attributes: key1, key2 and key3. Their values ​​are parameters a, b and c;

  • Delete the attribute named key3;

  • After the deletion is completed, traverse all the remaining attributes and return the values ​​of each attribute Strings formed by concatenating values, separated by,

Since JSON is used to transmit data, it must first store the data. Storing data requires a certain data format,JSON Commonly used data formats include JSON objects, JSON arrays and JSON strings.

What is a JSON object

JSON object (commonly called JSON) is a text data exchange format used to store and transmit data. An example is as follows:

{"name":"Jerry", "age":15}

This is a simple json object, its rules are:

  • Data exists in the form of key/value pairs;
  • Separate data with commas;
  • Braces indicate saving objects;
  • Square brackets indicate saving arrays.

The difference between JSON objects and Javascript objects

JSON is based on JavaScript syntax, so there is also the concept of objects in JSON, but there are some small differences from objects in JavaScript.

  1. Define a JavaScript object:
var myObject = {
    id:1,
    name:"Peter Bruce",
    "first name":"Bruce",
    display:function() {
                console.log(this.name);
            }}
  1. Define a JSON object:
{"id":1,"name":"Peter Bruce","first name":"Bruce"}
  1. Three differences:

(1)The attribute name (key) of the JSON object must be Be included in double quotes
, while JavaScript objects are arbitrary except that attribute names with spaces and attribute names with hyphens - in the middle must be enclosed in double quotes; (2) cannot be in Methods are defined in JSON objects, but in JavaScript objects
; (3)JSON objects can be operated by many languages, while JavaScript objects can only be recognized by JS itself

.
  1. The method of defining a JSON object is as follows

Included with a {}, and there are several internal A key-value pair composed of an attribute name and an attribute value. The key-value pairs are separated by, and the attribute name and attribute value are separated by :

. The attribute value can be any of the following data types. : Number, string, JSON array, JSON object, null. For example:

 {"a":1,"b":2.12,"c":true,"d":"string","e":null};
The situation where the attribute value is a JSON array or JSON object is slightly more complicated, which will be introduced in the following levels.

Using JSON objects in JavaScript

All languages ​​that support JSON can use JSON objects. Here we only introduce how to use JSON objects in JavaScript.
  • Define a JSON object in JavaScript:
    var jsonObject = {"name":"js","number":2};
  • To operate properties, use . or []
    • console.log(jsonObject.name);
      //读属性,输出jsconsole.log(jsonObject["name"]);
      //读属性,输出jsjsonObject.name = "javascript";
      //写属性,给name属性赋值javascript
    • Delete attributes, use delete:
      • var jsonObject = {"name":"js","number":2};
        delete jsonObject.name;
        //删除name属性
      • Traverse attributes , use for-in loop:
      • var jsonObject = {"name":"js","number":2};for(att in jsonObject) {
          console.log(jsonObject[att]);
          //依次输出js、2}

        Code file

        function mainJs(a,b,c) {
        	//请在此处编写代码
        	/********** Begin **********/
            var JSONObject = {"key1":a,"key2":b,"key3":c};
            delete JSONObject.key3;
            return a+","+b;
        	/********** End **********/}

        2, JSON array

        Task description

        Task for this level: Define and manipulate values ​​in JSON key-value pairs.

        The specific requirements are as follows:
        • It is known that the value of the third attribute of myJson is an array, the parameter a is a number, and it is required to add the first a element in the array (These elements are all string types) Splice them together, separate the elements with,, and return the spliced ​​string;
        • For example, when a is 2, you need to return js, java.

        The value (value) corresponding to the JSON attribute is an array
        • The value (value) in the JSON key-value pair can be an array

        For example:

        {"country":"China","population":"1.3billion","bigCity":["Peking","Shanghai","ShenZhen","HongKong"]}
        The attribute bigCity has multiple values, which are placed in an array.

        In the above example, each element of the array is a string. In fact, Each element of the array can also be another json object

        . For example:

        {"class":"高三一班","studentNumber":70,"score":[
            {"name":"LiMing","score":128},
            {"name":"ZhangHua","score":134},
            {"name":"ShenLu","score":112}]}
        The value of the score attribute above is an array, and each element of this array is a json object.

        Some operations on arrays
        1. Read and write elements:
          var myJson = {"country":"China","population":"1.3billion","bigCity":["Peking","Shanghai","ShenZhen","HongKong"]}console.log(myJson.bigCity[1]);
          //打印出ShanghaimyJson.bigCity[0] = "GuangZhou";
          //第一个元素被赋值为GuangZhou
        1. Traverse:

        var myJson = {"country":"China","population":"1.3billion","bigCity":["Peking","Shanghai","ShenZhen","HongKong"]}for(var i = 0;i < myJson.bigCity.length;i++) {
            console.log(myJson.bigCity[i]);//依次输出Peking,Shanghai,ShenZhen,HongKong}

        Code file

        [The first method was written later. At the beginning, I used the second method below. Because I couldn’t do it at the time, I thought about it directly. Output】

        var myJson = {
            "category":"computer",
            "detail":"programming",
            "language":[
            "js","java","php","python","c"
            ]}function mainJs(a) {
            a = parseInt(a);
        	//请在此处编写代码
        	/********** Begin **********/
            var b = "";
            for(var i=0;i<a;i++){
                b = b+myJson.language[i]+",";
            }
            return b.slice(0,-1);
        	/********** End **********/}
        var myJson = {
            "category":"computer",
            "detail":"programming",
            "language":[
            "js","java","php","python","c"
            ]}function mainJs(a) {
            a = parseInt(a);
        	//请在此处编写代码
        	/********** Begin **********/
            if(a==1){
                return myJson.language[0];
            }
            if(a==2){
                return myJson.language[0]+","+myJson.language[1];
            }
            if(a==3){
                return myJson.language[0]+","+myJson.language[1]+","+myJson.language[2];
            }
            if(a==4){
                return myJson.language[0]+","+myJson.language[1]+","+myJson.language[2]+","+myJson.language[3];
            }
            if(a==5){
                return myJson.language[0]+","+myJson.language[1]+","+myJson.language[2]+","+myJson.language[3]+","+myJson.language[4];
            }
        	/********** End **********/}

        3. JSON string

        Task description

        This level’s task: practice converting JSON strings and JavaScript objects to and from each other.

        Specific requirements are as follows:###
        1. 先将JSON字符串JSONString转换为JavaScript对象JSONObject;
        2. 然后将JSONObject的key1属性的值设置为mainJs()函数的参数a;
        3. 最后将JSONObject转换为JSON字符串,并返回该字符串

        在前端和后台之间传递数据可以使用JSON,但是实际上传递的是JSON字符串,而JSON对象是不可以直接进行传递的。

        JSON字符串

        JSON字符串就是在JSON对象两边套上'形成的字符串,如:

        var JSONObject  = {"k1":"v1","k2":"v2"};
        //JSON对象var JSONString1 = '{"k1":"v1","k2":"v2"}';
        //JSON字符串

        上面的JSONSring1就是JSON字符串,可以直接从前端传到后台或者后台传到前端。

        当JavaScript收到从后台传来的JSON字符串后,怎么把它变成JSON对象方便处理呢?

        JSON字符串到JavaScript对象

        JSON.parse(a,b)方法将JSON字符串a转换为JavaScript对象。b是一个可选的函数参数。

        var JSONString1 = '{"k1":"v1","k2":"v2"}';console.log(JSON.parse(JSONString1));
        //输出Object {k1: "v1", k2: "v2"}

        函数参数b按从里到外的顺序作用在对象的所有属性上,最后一个作用的是对象本身:

        //对象的每一个属性的值加1var text = '{ "key1":1, "key2":2, "key3":2.2}';var obj = JSON.parse(text, function (key, value) {
            if(key === '')//当遇到对象本身时,不进行加1操作
                return value;
            return value+1;//对属性值加1});console.log(obj);
            //输出Object {key1: 2, key2: 3, key3: 3.2}

        如上面所示,函数的参数有两个,其中key表示属性的名字,value表示属性的值,当遇到对象本身时,key的值为'',即空字符串。

        JSON对象转换为JSON字符串

        JSON.stringify(a,b,c)a是待转换的JSON对象,b和c为可选参数。

        var JSONObject = {"k1":"v1","k2":"v2"};
        JSON.stringify(JSONObject);
        //JSON对象转换为JSON字符串

        参数b为函数时,该函数按照从里到外的顺序处理JSON对象的每一个属性,最后一个处理的是JSON对象本身,处理完后再转为JSON字符串:

        //对象的所有属性值加1,再转为字符串var JSONObject = {"k1":1,"k2":2.2};var JSONString = JSON.stringify(JSONObject,function(k,v){
            if(k === '')//处理到了JSON对象本身
                return v;
            return v+1;//所有的属性的值加1});console.log(JSONString);
            //输出{"k1":2,"k2":3.2}

        参数b还可以是数组,数组存储的是属性的名字,用来指定只转换哪些属性:

        //转换对象中特定的属性
        var JSONObject = {"k1":1,"k2":2.2,"k3":3};var JSONString = JSON.stringify(JSONObject,["k1","k2"]);console.log(JSONString);
        //输出{"k1":1,"k2":2.2}

        这里简单介绍一下c:

        var str = ["name":"Tom","age":16];var obj1 = JSON.stringify(str);
        var obj2 = JSON.stringify(str,null,4);console.log(obj1);  
        //输出{"name":"Tom","age":16}console.log(obj2); 
        //输出
        //{
        //    "name": "Tom",
        //    "age": 16
        //}

        参数c:文本添加缩进、空格和换行符,如果 c 是一个数字,则返回值文本在每个级别缩进指定数目的空格,如果 c 大于 10,则文本缩进 10 个空格。

        代码文件

        var JSONString = '{"key1":"value1","key2":"value2"}';function mainJs(a) {
        	//请在此处编写代码
        	/********** Begin **********/
            var JSONObject = JSON.parse(JSONString);
            JSONObject["key1"] = a;
            JSONObject.key1 = a;
            return JSON.stringify(JSONObject);
        	/********** End **********/}

        相关推荐:javascript学习教程

        The above is the detailed content of JSON for JavaScript learning and understanding (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

        Statement:
        This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete