20.2 parsing and serialization "JavaScript Advanced Programming Third Edition"

Source: Internet
Author: User
Tags iso 8601 tojson

JSON is popular, and having a syntax similar to JavaScript is not the whole reason. One of the more important reasons is that you can parse the JSON data structure into useful JavaScript objects. The benefits of JSON parsing into JavaScript objects are extremely significant compared with the fact that XML data structures can be parsed into DOM documents and extracted from them. As an example of a JSON data structure that contains a set of books in the above section, after parsing to a JavaScript object, you can get the title of the third book by simply following a simple line of code:

Books[2].title

Of course, it is assumed that the objects obtained after parsing the JSON data structure are saved in the variable books. Let's look at the following code for finding data in the DOM structure:

Doc.getelementsbytagname ("book") [2].getattribute ("title")

Looking at these redundant method calls, it is not difficult to understand why JSON is warmly welcomed by JavaScript developers. Since then, JSON has become the de facto standard for exchanging data in Web services development.

20.2.1 JSON Object

The early JSON parser was basically the eval () function using JavaScript. Because JSON is a subset of JavaScript syntax, the eval () function can parse, interpret, and return JavaScript objects and arrays. ECMAScript 5 Defines the global object JSON as a specification for parsing JSON behavior. Browsers that support this object are IE 8+, Firefox 3.5+, Safari 4+, Chrome, and opera 10.5+. For earlier versions of the browser, you can use a shim:https://github.com/douglascrockford/json-js. In older browsers, using eval () to evaluate JSON data structures is risky because some malicious code might be executed. For browsers that cannot natively support JSON parsing, using this shim is the best choice.

There are two methods of JSON objects: Stringify () and parse (). In the simplest case, these two methods are used to serialize JavaScript objects into JSON strings and to parse JSON strings into native JavaScript values. For example:

var book = {title: "Professional JavaScript", Authors: ["Nicholas C. Zakas"],edition:3,year:2011};var Jsontext = json.str Ingify (book);

Run for a minute
This example uses Json.stringify () to serialize a JavaScript object into a JSON string and then save it in the variable jsontext. By default, the JSON string for the json.stringify () output does not contain any space characters or indents, so the string that is saved in Jsontext is as follows:

{"title": "Professional JavaScript", "authors": ["Nicholas C. Zakas"], "edition": 3, "Year": 2011}

When serializing a JavaScript object, all functions and prototype members are intentionally ignored and not reflected in the results. In addition, any property with a value of undefined will be skipped. The result is ultimately an instance property with a value of valid JSON data type.
Pass the JSON string directly to Json.parse () to get the corresponding JavaScript value. For example, you can create an object similar to book with the following code:

var bookcopy = Json.parse (Jsontext);

Note that although book and Bookcopy have the same properties, they are two independent objects that have no relationship.
If the string passed to Json.parse () is not a valid JSON, the method throws an error.

20.2.2 Serialization Options

In fact, json.stringify () can receive two additional parameters, in addition to the JavaScript object being serialized, that specify that the JavaScript object is serialized in a different way. The first parameter is a filter, which can be an array or a function, and the second argument is an option that indicates whether indentation is preserved in the JSON string. These two parameters can be used alone or in combination to control the serialization of JSON more thoroughly.

1. Filter results

If the filter parameter is an array, then the result of Json.stringify () will contain only the attributes listed in the array. Take a look at the following example.

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

Run for a minute
The second argument to Json.stringify () is an array that contains two strings: "title" and "edition". These two properties correspond to the attributes in the object that will be serialized, so only the two properties are included in the returned result string:

{"title": "Professional JavaScript", "edition": 3}

If the second argument is a function, the behavior is slightly different. The incoming function receives two parameters, a property (key) name, and a property value. Depending on the name of the property (key), you know how to handle the properties in the object that you want to serialize. The property name can be only a string, and the key name may be an empty string when the value is not a value of a key-value pair.
To change the result of a serialized object, the value returned by the function is the value of the corresponding key. Note, however, that if the function returns undefined, the corresponding property is 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;}});

Run for a minute
Here, the function filter determines the result based on the key passed in. If the key is "authors", the array is concatenated as a string, if the key is "year", its value is set to 5000, and if the key is "edition", the property is deleted by returning undefined.
Finally, be sure to provide the default item, and return the value passed in so that other values will appear correctly in the results. In fact, the first time you call this function filter, the passed-in key is an empty string, and the value is the book object. The serialized JSON string resembles the following:

{"title": "Professional JavaScript", "Authors": "Nicholas C. Zakas", "Year": 5000}

Each object in the object to be serialized is filtered so that each object in the array with these attributes is filtered, and each object contains only the title, authors, and year properties.

Firefox 3.5 and 3.6 for the implementation of Json.stringify () has a bug, when the function as the second parameter of the method, the bug will appear, that the function can only be used as a filter: return undefined means to skip a property, Any other value returned will include the corresponding property in the result. Firefox 4 Fixes this bug.
2. String indentation

The third parameter of the Json.stringify () method is used to control the indentation and whitespace characters in the result. If this parameter is a numeric value, it represents the number of spaces indented at each level. For example, to indent 4 spaces at each level, you can write code like this:

var book = {    "title": "Professional JavaScript",    "authors": ["Nicholas C. Zakas"],    Edition:3, year    : 2011};var Jsontext = json.stringify (book, NULL, 4);

Run for a minute

The strings that are saved in Jsontext are as follows:

{    "title": "Professional JavaScript",    "authors": ["Nicholas C. Zakas"],    "edition": 3,    "Year": 2011}

Unaware of the reader's attention, json.stringify () also inserted line breaks in the result string to improve readability. As soon as you pass in a valid control indent parameter value, the resulting string will contain a newline character. (It's not very meaningful to just shrink and not wrap.) The maximum number of indent spaces is 10, and all values greater than 10 are automatically converted to 10.
If the indent parameter is a string rather than a numeric value, the string is used as the indent character in the JSON string (no longer using spaces). In the case of strings, you can set the indent character to a tab, or any character such as two dashes.

var jsontext = json.stringify (book, NULL, "--");

In this way, the string in the Jsontext will become as follows:

{--"title": "Professional JavaScript",--"authors": [----"Nicholas C. Zakas"--],--"edition": 3,--"Year": 2011}

The indent string cannot be longer than 10 characters long. If the string is longer than 10, only the first 10 characters will appear in the result.

3. ToJSON () method

Sometimes, json.stringify () does not satisfy the need for custom serialization of certain objects. In these cases, you can define the Tojson () method for the object, returning its own JSON data format. The native Date object has a Tojson () method that automatically converts the JavaScript date object to an ISO 8601 day string (exactly as the result of calling Toisostring () on a Date object).
You can add a Tojson () method to any object, such as:

var book = {"title": "Professional JavaScript", "authors": ["Nicholas C. Zakas"],edition:3,year:2011,tojson:function () { return this.title;}; var jsontext = json.stringify (book);

Run for a minute
The above code defines a Tojson () method on the book object that returns the title of the books. Like a Date object, this object is also serialized as a simple string rather than an object. You can have the Tojson () method return any value and it will work correctly. For example, this method can be returned to undefined, at which point the object containing it is embedded in another object, causing its value to become null, and if it is a top-level object, the result is undefined.
ToJSON () can be supplemented as a function filter, so it is important to understand the internal order of serialization. Suppose you pass an object into Json.stringify () and serialize the object in the following order.
(1) if the Tojson () method is present and can be used to obtain a valid value, the method is called. Otherwise, the object itself is returned.
(2) If the second parameter is provided, apply this function filter. The value passed into the function filter is the value returned by step (1).
(3) The corresponding serialization of each value returned by step (2).
(4) If a third parameter is provided, the corresponding formatting is performed.
Whether you are considering defining the Tojson () method, or considering using a function filter, or need to use both, it is important to understand the order.

20.2.3 parsing 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 substitution (filter) function (Replacer) received by Json.stringify (), this function is called a restore function (Reviver), but in fact the signatures of the two functions are the same-they all receive two arguments, a key and a value, and all need to return a value.
If the Restore function returns undefined, the corresponding key is removed from the result, and if another value is returned, the value is inserted into the result. A restore function is often used when converting a date string to a data date object. For example:

var book = {"title": "Professional JavaScript", "authors": ["Nicholas C. Zakas"],edition:3,year:2011,releasedate:new Dat E (1)};var jsontext = json.stringify (book), var bookcopy = Json.parse (Jsontext,function (key, value) {if (key = = "R Eleasedate ") {return new Date (value);} else {return value;}}); Alert (BookCopy.releaseDate.getFullYear ());

Run for a minute
The above code first adds a ReleaseDate property to the book object, which holds a date object. This object is serialized into a valid JSON string, then parsed and reverted to a Date object in Bookcopy. When the restore function encounters the "ReleaseDate" key, a new Date object is created based on the corresponding value. The result is that a date object is saved in the Bookcopy.releasedate property. Because of this, the getFullYear () method can be called based on this object.

More Chapters Tutorial: http://www.shouce.ren/api/view/a/15218

20.2 parsing and serialization "JavaScript Advanced Programming Third Edition"

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.