Interaction between js and json: Theory and example

Source: Internet
Author: User
Tags iso 8601 iso 8601 date tojson

Interaction between js and json: Theory and example

 

JSON syntax can represent the following three types of values.
? Simple Value: Use the same syntax as JavaScript to represent strings, values, Boolean values, and null in JSON.
JSON does not support special undefined values in JavaScript.
? Object: An object, as a complex data type, represents a group of unordered key-value pairs. The value in each key-value pair can be
It can be a simple value or a value of a complex data type.
? Array: An array is also a complex data type, indicating a list of ordered values. You can access the list through numerical indexes.
. 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 that represents structured data.
Some syntaxes of data are the same, but it is not limited to JavaScript.
Distinct 1.1 simple value

The simplest JSON data format is simple value. For example, the following value is valid JSON data:

5
This is the JSON representation of the value 5. Similarly, the following is a JSON string representation method:
Hello world!
The biggest difference between a JavaScript string and a JSON string is that a JSON string must use double quotation marks.
Method error ).

Boolean values and null values are also valid in JSON format. However, in actual applications, JSON is more used to represent more complex data.
Structure, while simple values are only part of the entire data structure.
V1.1.2 object
The objects in JSON are slightly different from those in JavaScript. The following is the object literal in JavaScript:
Var person = {
Name: Nicolas,
Age: 29
};
Although this is the standard way for developers to create the literal volume of objects in JavaScript, the objects in JSON must be cited for attributes.
. In fact, in JavaScript, the preceding object literal can be written as follows:
Var object = {
Name: Nicolas,
Age: 29
};
JSON indicates the preceding object as follows:
{
Name: Nicolas,
Age: 29
}
Compared with the JavaScript Object literal, The JSON object has two differences.

First, no variables are declared (no variable concept in JSON ).

Second, there is no semicolon at the end (because this is not a JavaScript statement, you do not need a semicolon ).

Again,
The property of the object must be enclosed in double quotation marks, which is required in JSON. Attribute values can be simple values or complex type values, because
You can embed an object in the object as follows:
{
Name: Nicolas,
Age: 29,
School :{
Name: Merrimack College,
Location: North Andover, MA
}
}
This example embeds school Information in top-level objects. Although there are two name attributes
It is a different object, so there is no problem. However, two attributes with the same name must not appear in the same object.
Unlike JavaScript, attribute names of objects in JSON must be enclosed in double quotation marks at any time. When writing JSON manually, I forgot
It is a common mistake to add double quotation marks to the attribute name or write the double quotation marks as single quotation marks.

Release 1.3 Array
The second complex data type in JSON is array. The JSON array uses the array literal form in JavaScript. Example
For example, the following is the array literal in JavaScript:
Var values = [25, hi, true];
In JSON, the same syntax can be used to represent the same array:
[25, hi, true]
Likewise, JSON arrays do not contain variables or semicolons. Combining arrays with objects can form more complex data sets,
For example:
[
{
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 3,
Annual: 2011
},
{
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 2,
Annual: 2009
},
{
Title: Professional Ajax,
Authors :[
Nicolas C. Zakas,
Jeremy McPeak,
Joe Fawcett
],
Edition: 2,
Annual: 2008
},
{
Title: Professional Ajax,
Authors :[
Nicolas C. Zakas,
Jeremy McPeak,
Joe Fawcett
],
Edition: 1,
Annual: 2007
},
{
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 1,

Annual: 2006
}
]
This array contains some objects that indicate books. Each object has several attributes, one of which is authors.
The attribute value is an array. Objects and arrays are usually the outermost form of the JSON data structure (of course, this is not mandatory ),
They can be used to create a variety of data structures.
20.2 parsing and serialization
Not all of the reasons why JSON is popular are similar to JavaScript syntax. One more important reason is that you can
Parse JSON data structures into useful JavaScript objects. The XML data structure should be parsed into a DOM document and extracted data from it
Compared with JSON, JSON can be parsed into JavaScript objects. The preceding section contains the JSON
For example, after parsing the data structure as a JavaScript Object, you only need the following simple code to obtain the title of the third book:
Books [2]. title
Of course, it is assumed that the object obtained after parsing the JSON data structure is saved to the variable books. Let's take a look at the DOM below.
Code for searching data in the structure:
Doc. getElementsByTagName (book) [2]. getAttribute (title)
Looking at these redundant method calls, it is not difficult to understand why JSON can be warmly welcomed by JavaScript developers. Slave
After that, JSON becomes the de facto standard for data exchange in Web service development.
20.2.1 JSON object
The early JSON parser basically used JavaScript's eval () function. JSON is a child of JavaScript syntax.
Therefore, the eval () function can parse, interpret, and return JavaScript objects and arrays. ECMAScript 5 parses JSON lines
The Global Object JSON is defined for standardization. Browsers that support this object include IE 8 +, Firefox 3.5 +, Safari 4 +, and Chrome
And Opera 10.5 +. For earlier browsers, you can use a shim: https://github.com/douglascrockford/json-js.
In earlier versions of browsers, using eval () to evaluate the JSON data structure is risky because malicious code may be executed.
This shim is the best choice for browsers that do not support native JSON parsing.
The JSON object has two methods: stringify () and parse (). In the simplest case, the two methods are used
The JavaScript Object is serialized as a JSON string and parsed as a native JavaScript value. For example:
Var book = {
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 3,
Annual: 2011
};
Var jsonText = JSON. stringify (book );

This example usesJSON. stringify () serialize a JavaScript object into a JSON stringAnd then save it
The variable jsonText exists. By default, the JSON string output by JSON. stringify () does not contain any space characters or
Indent, so the string stored in jsonText is as follows:
{Title: Professional JavaScript, authors: [Nicolas C. Zakas], edition: 3, year: 2011}
When serializing JavaScript objects, all functions and prototype members are intentionally ignored and not reflected in the results.In addition, the value is
Any attributes of undefined will also be skipped. In the result, all instance properties with valid JSON data types are final.
Pass the JSON string directly to JSON. parse () to obtain the corresponding JavaScript value.. For example, use the following code:
You can create an object similar to book:
Var bookCopy = JSON. parse (jsonText );
Note: although book and bookCopy have the same attributes, they are two independent objects with no relationship.
If the string passed to JSON. parse () is not a valid JSON string, this method throws an error.
Serialization 2.2 serialization options
In fact, in addition to the JavaScript Object To be serialized, JSON. stringify () can also receive two other parameters.
Parameters are used to specify how JavaScript objects are serialized in different ways. The first parameter is a filter, which can be an array or
The second parameter is an option, indicating whether to retain indentation in the JSON string. Use either of the two
Parameters to control JSON serialization in a more comprehensive and in-depth manner.
1. filter results
If the filter parameter is an array, the result of JSON. stringify () will only contain the attributes listed in the array. Let's see
.
Var book = {
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 3,
Annual: 2011
};
Var jsonText = JSON. stringify (book, [title, edition]);
JSONStringifyExample01.htm
The second parameter of JSON. stringify () is an array containing two strings: title and edition.This
The two attributes correspond to the attributes in the object to be serialized. Therefore, only the two attributes are included in the returned result string:
{Title: Professional JavaScript, edition: 3}

If the second parameter is a function, the behavior is slightly different. The input function receives two parameters: attribute (key) Name and attribute value. Root
The data property (key) Name knows how to process the attributes in the object to be serialized. The attribute name can only be a string, but the key name can be a null string when the value is not a key-Value Pair structure value.
To change the result of the serialized object, the value returned by the function is the value of the corresponding key. However, if the function returns

Undefined, then the corresponding attributes will be ignored. Let's look at an example.

Var book = {
Title: Professional JavaScript,
Authors: [Nicolas C. Zakas, xxxx. xxx],
Edition: 3,
Annual: 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;
}
});

Console. log (jsonText); // {title: Professional JavaScript, authors: Nicholas C. Zakas, xxxx. xxx, year: 5000}


Here, the function filter determines the result based on the input key. If the key is authors, the array is connected to a string;
If the key is year, the value is set to 5000. If the key is edition,Return undefined to delete the attribute.
Finally, you must provide the default item. At this time, the input value is returned so that other values can appear normally in the result. In fact
When this function filter is called at one time, the input key is an empty string and the value is the book object. Serialized JSON string
As follows:
{Title: Professional JavaScript, authors: Nicholas C. Zakas, year: 5000}
Each object in the object to be serialized must pass the filter. Therefore, each object in the array with these attributes is filtered.
Then, each object only contains the title, authors, and year attributes.
Firefox 3.5 and 3.6 have a bug in the implementation of JSON. stringify (). When using a function as the second parameter of this method
This bug occurs, that is, this function can only be used as a filter: Returning undefined means skipping a property and returning it
Any value of this parameter will contain corresponding attributes in the result. Firefox 4 fixed this bug.
2. String indent
The third parameter of the JSON. stringify () method is used to control indentation and blank spaces in the result.
If this parameter is a number
Value, which indicates the number of spaces for each level of indentation. For example, to indent four spaces at each level, you can write the code as follows:
Var book = {
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 3,
Annual: 2011

};
Var jsonText = JSON. stringify (book, null, 4 );
JSONStringifyExample03.htm
The strings saved in jsonText are as follows:
{
Title: Professional JavaScript,
Authors :[
Nicolas C. Zakas
],
Edition: 3,
Annual: 2011
}
I don't know whether the reader noticed it. JSON. stringify () also inserts a line break in the result string to improve readability. As long
Input a valid parameter value that controls indentation. The result string contains a line break. (Indent only, but not line feed is of little significance. ) The maximum indentation is null.
If the number of cells is 10, all values greater than 10 are automatically converted to 10.
If the indent parameter is a string rather than a numeric value, the string will be used as an indent character in the JSON string (no longer
Use space ). When using a string, you can set the indent character to a Tab character or any character such as two dashes.
Var jsonText = JSON. stringify (book, null ,--);
In this way, the strings in jsonText will become as follows:
{
-- Title: Professional JavaScript,
-- Authors :[
---- Nicolas C. Zakas
--],
-- Edition: 3,
-- Year: 2011
}
The length of the Indented string cannot exceed 10 characters. If the length of a string exceeds 10 characters, only the first 10 words will appear in the result.
.
3. toJSON () method
Sometimes, JSON. stringify () still cannot meet the custom serialization requirements for some objects. In these cases,
You can define the toJSON () method for an object and return its own JSON data format.The native Date object has a toJSON () method,
The Date object in JavaScript can be automatically converted to an ISO 8601 Date string (same as the Date object that calls toISOString ()
).You can add the toJSON () method to any object.For example:

Var book = {
Title: Professional JavaScript,
Authors: [Nicolas C. Zakas],
Edition: 3,
Year: 2011,
ToJSON: function (){
Return this. title;
}
};
Var jsonText = JSON. stringify (book );
Console. log (jsonText); // Professional JavaScript


The code above defines a toJSON () method on the book object, which returns the book title. Similar to the Date object,
This object will also be serialized into a simple string instead of an object. The toJSON () method can return any value.
Work. For example, you can let this method return undefined. If the object containing it is embedded in another object
Its value becomes null, and if it is a top-level object, the result is undefined.
ToJSON () can be used as a supplement to function filters. Therefore, it is very important to understand the internal sequence of serialization.. Assume that an object is passed
Input JSON. stringify () and serialize the object in the following sequence.
(1) If the toJSON () method exists and a valid value can be obtained through it, this method is called. Otherwise, the object itself is returned.
(2) If the second parameter is provided, apply this function filter. The value of the input function filter is the value returned in step (1.
(3) serialize each value returned in step (2.
(4) If the third parameter is provided, format it accordingly.
Whether you want to define the toJSON () method, use function filters, or use both of them to understand this
Order is crucial.
Resolution options
The JSON. parse () method can also receive another parameter, which is a function that will be called on each key-value pair. To
Difference the replacement (filter) function received by JSON. stringify (), which is called the restoration function (reviver ),
But in fact the signatures of these two functions are the same-they both receive two parameters, one key and one value, and both need to return one
.
If the restore function returns undefined, the corresponding key is to be deleted from the result. If other values are returned, the value is inserted.
To the result. The restoration function is often used to convert a Date string to a Date object. For example:

Var book = {
Title: Professional JavaScript,
Authors: [Nicolas C. Zakas],
Edition: 3,
Year: 2011,
ReleaseDate: new Date (2011, 11, 1) // Add
};
Var jsonText = JSON. stringify (book );
Var bookCopy = JSON. parse (jsonText,
Function (key, value ){
If (key = releaseDate ){
Return new Date (value );
} Else {
Return value;
}
});
Console. log (bookCopy. releaseDate. getFullYear (); // 2011

The code above first adds a releaseDate attribute to the book object, which stores a Date object. This
After being serialized, the object becomes a valid JSON string, which is parsed and restored to a Date in bookCopy.
Object. When the releaseDate key is encountered, the restoration function creates a new Date object based on the corresponding value. The result is
A Date object is saved in the bookCopy. releaseDate attribute. Because of this, this object can be called based on
GetFullYear () method.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.