20. Introduction to JSON

20. Introduction to JSON

JSON is a strict subset of JavaScript and uses some patterns in JavaScript to represent structured data.
Regarding JSON, the most important thing is to understand that it is a data format, not a programming language. Although it has the same grammatical form, JSON is not subordinate to JavaScript. Moreover, JSON is not only used by JavaScript, after all, JSON is just a data format. Many programming languages ​​have parsers and serializers for JSON.

1.JSON syntax

The syntax of JSON can represent the following three types of values.

  • Simple values: Using the same syntax as JavaScript, strings, numbers, booleans, and null can be represented in JSON.
    But JSON does not support the special value undefined in JavaScript.
  • Object: As a complex data type, an object represents a set of unordered key-value pairs. The value in each key-value pair can be a
    simple value or a value of a complex data type.
  • Array: Array is also a complex data type, which represents a set of ordered list of values, the values ​​can be accessed through numerical index
    . The value of an array can also be of any type-simple value, object or array.

JSON does not support variables, functions, or object instances. It is a format for representing structured data. Although it has the same syntax as JavaScript for representing data, it is not limited to the scope of JavaScript.

1.1 Simple value

The simplest form of JSON data is a simple value. Such as strings, numbers.

1.2 Target

Objects in JSON are slightly different from JavaScript literals. as follows:

The JSON representation of objects is as follows:

{
    
    
    "name": "Nicholas",
    "age": 29
}

Unlike JavaScript, the property names of objects in JSON must be enclosed in double quotes at all times. When writing JSON by hand, it
is a common mistake to forget to add double quotes to the object property name or to write double quotes as single quotes.

1.3 Array

In JSON, the same syntax can be used to represent the same array:

[25, "hi", true]

Also note that there are no variables and semicolons for JSON arrays. Combining arrays and objects can form more complex data collections,

2. JSON parsing and serialization

Why is JSON needed for conversion?

The popularity of JSON is not the whole reason that it has a syntax similar to JavaScript. A more important reason is that the
JSON data structure can be parsed into useful JavaScript objects. Compared with the XML data structure to be parsed into a DOM document and extracting data from it is extremely troublesome, the advantage of JSON can be parsed into a JavaScript object is extremely obvious. Take the JSON data structure of a group of books in the previous section as an example. After being parsed as a JavaScript object, the title of the third book can be obtained with the following simple line of code:
books[2].title
Of course, Here it is assumed that the object obtained after parsing the JSON data structure is saved in the variable books. Take a look at the following code to find data in the DOM structure:
doc.getElementsByTagName("book")[2].getAttribute("title")
Look at these redundant method calls, it is not difficult to understand why JSON can be obtained by JavaScript developers A warm welcome. Since then, JSON has become the de facto standard for data exchange in Web service development.

2.1 JSON object

JSON objects are global variables defined by Javascript.
JSON objects have two methods: stringify() and parse() . In the simplest case, these two methods are used to
serialize JavaScript objects into JSON strings and parse JSON strings into native JavaScript values.

2.2 Serialization options

In fact, in addition to the JavaScript object to be serialized, JSON.stringify() can also receive two other parameters. These
two parameters are used to specify different ways to serialize the JavaScript object. The first parameter is a filter, which can be an array or
a function; the second parameter is an option that indicates whether to keep indentation in the JSON string. These two
parameters can be used alone or in combination to control the serialization of JSON more comprehensively and deeply.
1. Filter the result
If the filter parameter is an array, the result of JSON.stringify() will only contain the attributes listed in the array.

var book = {
    "title": "Professional JavaScript",
    "authors": [
        "Nicholas C. Zakas"
    ],
    edition: 3,
    year: 2011
};

var jsonText = JSON.stringify(book, ["title", "edition"]);

If the second parameter is a function, the behavior will be slightly different. The incoming function receives two parameters, the attribute (key) name and the attribute value. Root
According to property (key) name should know how to deal with the serialization of object attributes. The attribute name can only be a string, and when the value is not the
value of a key- value pair structure, the key name can be an empty string.

Note, however, that if the function returns undefined, the corresponding properties will be ignored. Let's look at an example.

var book = {
    "title": "Professional JavaScript",
    "authors": [
        "Nicholas C. Zakas"
    ],
    edition: 3,
    year: 2011
    };
    
var jsonText = JSON.stringify(book, function(key, value){
    switch(key){
        case "authors":
            return value.join(",")
        case "year":
            return 5000;
        case "edition":
            return undefined;
        default:
            return value;
    }   
});

2. String indentation
The third parameter of the JSON.stringify() method is used to control the indentation and whitespace in the result. If this parameter is a numeric value, it represents the number of spaces for each level of indentation.
If the indentation parameter is a string instead of a numeric value, this string will be used as an indentation character in the JSON string (
spaces are no longer used). In the case of using a string, you can set the indentation character to a tab character, or any character such as two dashes

2.3 Analysis options

The JSON.parse() method can also receive another parameter, which is a function that will be called on each key-value pair. In order to distinguish the replacement (filtering) function (replacer) received by JSON.stringify(), this function is called a restorer, but in fact the signatures of these two functions are the same-they both receive two parameters, A key and a value, and both need to return a
value.
If the restore function returns undefined, it means that the corresponding key is to be deleted from the result; if it returns another value, the value is inserted into the result. When converting a date string to a Date object, the restore function is often used. E.g:

var book = {
    "title": "Professional JavaScript",
    "authors": [
        "Nicholas C. Zakas"
    ],
    edition: 3,
    year: 2011,
    releaseDate: new Date(2011, 11, 1)
    };
    
var jsonText = JSON.stringify(book);

var bookCopy = JSON.parse(jsonText, function(key, value){
    if (key == "releaseDate"){
        return new Date(value);
    } else {
        return value;
    }
};

summary

JSON is a lightweight data format that can simplify the workload of representing complex data structures. JSON uses
a subset of JavaScript syntax to represent objects, arrays, strings, numbers, Boolean values, and null. Even XML can represent the same complex data results, but
JSON is less cumbersome and it is more convenient to use in JavaScript.

ECMAScript 5 defines a native JSON object, which can be used to serialize objects into JSON strings or
parse JSON data into JavaScript objects. The JSON.stringify() and JSON.parse() methods are used to implement the above two functions respectively.
These two methods have some options, through which you can change the filtering method or change the serialization process.

Test code

// json转换js对象为json字符串
var book = {
	title: "js",
	authors: ["Nike"],
	edition: 3,
	year: 2011,
};

var JsonText = JSON.stringify(book, ["title", "authors"], 4);

// json第二个参数使用方法实例
var book = {
	title: "js",
	authors: ["Nike"],
	edition: 3,
	year: 2011,
}

var jsonText = JSON.stringify(book, function(key, value){
	switch(key){
		case "authors":
			return value.join(".");

		case "year":
			return 5000;

		case "edition":
			return undefined;

		default:
			return value;
	}
});

// 解析json
var book = {
	title: "js",
	authors: ["Nike"],
	edition: 3,
	year: 2011,
	releaseDate: new Date(2019, 6, 4)
};



function(key, value){if (key == "releaseDate"){ return new Date(value);} else { return value;}}



var book = {
	title: "js",
	authors: ["Nike"],
	edition: 3,
	year: 2011,
	releaseDate: new Date(2019, 6, 4),
};


var book2 = JSON.parse(jsonText, function(key, value){
	if (key == "releaseDate"){ 
		return new Date(value);
	} else { 
		return value;
	}});

Guess you like

Origin blog.csdn.net/sinat_23931991/article/details/90813601