JSON Explained

JSON is now widely used for front-end and back-end data interaction and is the most popular interactive data format. A data format is a text format that is passed between different platforms. The full name of JSON is Java Script Object Notation (JavaScript Object Notation), the meaning of the notation, the character system used to represent data such as numbers or words.

Classification of JSON

1. Simple JSON object

{name”:"Curry",
    “age”:20
}

That's right, direct measurement

//键值名带引号
var person = {
    “name”:"Curry",
    “age”:20
};
console.log(type.person); //Object

//键值名不带引号
var person = {
    name:Curry,
    age:20
};
console.log(type.person); //Object

The difference between the two:

  • Object literals have declared variables (not in JSON)
  • Object literals are JavaScript statements, so there is a ";" at the end
  • Object literal key value name quotes are optional, and JSON must have quotes

complex JSON objects

["Curry", 12]
//

[ 
    {
        "name":"Curry",
        "age": 12
    }
]

//
[
    {
        "name":"Curry",
        "age":12,
        "like":["eat","drink"]
    },
    {
        "name":"Curry",
        "age":12,
        "like":["eat","drink"]
    }
]
//
[
    {
        "name":"Curry",
        "age":12,
        "like":{
            "eat":"banner",
            "drink":"water"
        }
    },
    {
        "name":"Curry",
        "age":12,
        "like":{
            "eat":"banner",
            "drink":"water"
        }
    }
]

The json array data is deepened layer by layer, so it can represent complex data

JSON strings and JSON objects
Sometimes JSON strings are passed from the background, and we treat them as JavaScript objects and call methods, which will naturally make mistakes.
1.stringify() method - parameters (required)

var person={
    "name":"Curry",
    "age":12
};
console.log(typeof person); //Object

var jsonString = JSON.stringify(peson);
console.log(typeof jsonString); //String

The usage is: convert the object object into a json string
Type conversion: Object–>String
2.parse() method—>parameters

var person = {
    "name":"Curry",
    "age":12
};
console.log(typeof myMes);//Object

//模拟json字符串
var jsonString = JSON.stringify(myMes);
console.log(typeof jsonString);//String

var jsonObject = JSON.parse(jsonText);
console.log(typeof jsonObject); //Object

The usage is as above, the function is to convert the json string into a json object. In order to simulate the json string, we first use the stringify method to create a json string.
Type change: String -> Object

JSON serialization
stringify() can accept the second parameter, [filter condition], and return the filtered json object
Array condition filtering, such as ["name", "age"]

var person = {
        "name": "Curry",
        "age": 20,
        "like": "drink",
        "nationality": "China"
    };
//实现过滤,只留下name和age  
var jsonString = JSON.stringify(person,["name","age"]);
cosole.log(jsonString);  //{"name":"Curry","age":"20"}

Function filtering
When using function conditional filtering, we can do the processing according to our needs

var person = {
        "name": "Curry",
        "age": 20,
        "like": "drink",
        "nationality": "China"
    };

var jsonString = JSON.stringify(person,function(key, value){
    switch(key){
        case "name":
            return "KD"
        default:
            return value;
    }

},4);
//{"name":"KD","age":12,"like": "drink","nationality": "China"}

For the third parameter, the usage of 4 in the above code, as described below, about this function filtering function (key, value) {}, key is the name of the key-value pair, and value stores the value

JSON string format serialization
is to use the third parameter of stringify()

 var myMes= {
        "name": "ys",
        "age": 12,
        "like": "drink",
        "nationality": "China"
    };
    var jsonText = JSON.stringify(myMes, ["name","age"],4);
    console.log(jsonText); //{"name": "ys", "age": 12}

As in the above code, we set the third parameter to stringify(), [indentation control]

The toJSON() method
implements a custom serialization method with priority execution

var person = {
    "name":"Curry",
    "age":12,
    toJSON:function(){
    }
};

var jsonString = JSON.stringify(person);
console.log(jsonString);  //"Curry"

Execution mechanism:
If there is a toJSON() method and a valid value can be obtained through it, call the method, otherwise return the object itself.
After getting the value through the first step, if there is a filter function, pass the return value to the filter After the function is serialized
by the filter function, if there is a third parameter [Format Control], it will be formatted.

JSON parsing
json string contains objects how to correctly
parse the usage of the second parameter of parse(), we also call him "reduction function"

//定义一个构造对象的方法
function setMessage(eat, drink){
    this.eat=eat;
    this.drinl = drink;
    this.getEat= function(){
        return this.eat;
    };
}
//定义一个myName的对象
var = myMessi = {
    "name":"Curry",
    "age": 12,
    "message": new setMessage("banana", "water")
};

//模拟json字符串
var jsonString= JSON.stringify(myMes);
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.message);  //{eat: 'banana',drink:'water'}

Yes, it can be accessed, then I want to access the getEat() method, call it, and I am surprised to find that it is wrong. Is there something wrong with our code? At this point, our new setMessage() loses the functionality of the object. You may think that we are just converting simulations. In fact, the actual development process is like this. When the data is transmitted, it also goes through Object -> String -> Object (the object is encapsulated in the background, the transmission becomes string, and it is parsed into Object). The problem arises. Then naturally there is a solution.

//定义一个构造方法
function setMessage(eat, drink){

        this.eat = eat;
        this.drink = drink;
        this.getEat = function(){
            return "你想吃" + this.eat;
        };
    }
//定义一个myName的对象 
    var myMes = {
        "name": "ys",
        "age": 12,
        "message": new setMessage("banana", "water")
    };
    //为了模拟json字符串
    var jsonText = JSON.stringify(myMes);

    var jsonObj = JSON.parse(jsonText, function(key, value){
        switch(key){
            case "message":
                return new setMessage(value.eat, value.drink);
            default:
                return value;
        }
    });
    console.log(jsonObj.message.getEat());  //你想吃banana

In fact, we can see that as long as there are function parameters, we can use functions to achieve many functions, but it is more scalable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325759768&siteId=291194637