JS and JSON interaction theory and examples

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

The theory and technique are explained in detail, the practical development work is of great significance.


The syntax of JSON can represent the following three types of values.
 Simple Values: Using the same syntax as JavaScript, you can represent strings, numeric values, Booleans, and Null in JSON.
However, JSON does not support special value undefined in JavaScript.
 Object: An object is a complex data type that represents a set of unordered key-value pairs. The values in each key-value pair can be
Either a simple value or a value of a complex data type.
 Array: An array is also a complex data type that represents a list of ordered sets of values that can be accessed by a numeric index
The value. The value of an array can also be any type-a simple value, an object, or an array.
JSON does not support variables, functions, or object instances, it is a format for representing structured data, although it is represented in JavaScript
Some of the syntax of the data is the same, but it is not limited to JavaScript.
20.1.1 Simple Values

The simplest form of JSON data is simple values. For example, the following value is a valid JSON data:

5
This is how JSON represents the value 5. Similarly, here's how JSON represents a string:
"Hello world!"
The biggest difference between a JavaScript string and a JSON string is that the JSON string must use double quotation marks (a single quotation mark causes the language
Error).

Boolean values and Null are also valid JSON forms. However, in real-world applications, JSON is more used to represent more complex data
structure, and simple values are just a subset of the entire data structure.
20.1.2 Object
The object in JSON is slightly different from the JavaScript literal. Here is the object literal in a JavaScript:
var person = {
Name: "Nicholas",
Age:29
};
While this is a standard way for developers to create object literals in JavaScript, objects in JSON require attributes to be cited
No. In fact, in JavaScript, the preceding object literal can be written as follows:
var object = {
"Name": "Nicholas",
"Age": 29
};
JSON represents the above objects in the following way:
{
"Name": "Nicholas",
"Age": 29
}
There are two different locations for JSON objects compared to the object literals of JavaScript.

First, there are no declared variables (the concept of no variables in JSON).

Second, there is no semicolon at the end (because this is not a JavaScript statement, so semicolons are not required).

Again, the properties of the
object must be enclosed in double quotes, which is required in JSON. The value of a property can be a simple value, or a complex type value, because
can embed an object in an object as follows:
{
"name": "Nicholas",
"age": School,
"name": " Merrimack College ",
" location ":" North Andover, MA "
}
}
This example embeds the school (" school ") information in the top-level object. There are two "name" properties, but since they are
separate objects, there is absolutely no problem. However, there should never be two identically named properties in the same object.
Unlike JavaScript, the property name of an object in JSON must be double-quoted at any time. When writing JSON manually, it is common to forget to add double quotes to
like attribute names or to write double quotation marks as single quotes.

20.1.3 Array
The second complex data type in JSON is an array. The JSON array takes the form of an array literal in JavaScript. Cases
For example, here is the array literal in JavaScript:
var values = [+, "HI", true];
In JSON, you can use the same syntax to represent the same array:
[+, "HI", true]
Also note that JSON arrays do not have variables and semicolons. Combining arrays and objects can form a more complex set of data,
For example:
[
{
"title": "Professional JavaScript",
"Authors": [
"Nicholas C. Zakas"
],
Edition:3,
year:2011
},
{
"title": "Professional JavaScript",
"Authors": [
"Nicholas C. Zakas"
],
Edition:2,
year:2009
},
{
"title": "Professional Ajax",
"Authors": [
"Nicholas C. Zakas",
"Jeremy McPeak",
"Joe Fawcett."
],
Edition:2,
year:2008
},
{
"title": "Professional Ajax",
"Authors": [
"Nicholas C. Zakas",
"Jeremy McPeak",
"Joe Fawcett."
],
Edition:1,
year:2007
},
{
"title": "Professional JavaScript",
"Authors": [
"Nicholas C. Zakas"
],
Edition:1,

year:2006
}
]
This array contains some objects that represent books. Each object has several properties, one of which is "authors", which
The value of the property is another array. Objects and arrays are usually the outermost form of a JSON data structure (of course, this is not mandatory),
Use them to create a variety of data structures.
20.2 parsing and serialization
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 put
The JSON data structure resolves to a useful JavaScript object. and XML data structures to parse into DOM documents and extract data from them
The benefits of JSON parsing into JavaScript objects are extremely significant compared to the most troublesome. JSON that contains a set of books in the section above
Data structure For example, after parsing to a JavaScript object, only need the following line of simple code to get the title of the third book:
Books[2].title
Of course, it is assumed that the objects obtained after parsing the JSON data structure are saved in the variable books. And look at the DOM below.
Code to find data in the 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. From
After that, JSON becomes 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 child of JavaScript syntax
Set, the eval () function can parse, interpret, and return JavaScript objects and arrays. ECMAScript 5 pairs of rows parsing JSON
For specification, the global object JSON is defined. 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, the two methods are used to separate the
JavaScript objects are serialized into JSON strings and JSON strings are parsed into native JavaScript values. For example:
var book = {
Title: "Professional JavaScript",
Authors: [
"Nicholas C. Zakas"
],
Edition:3,
year:2011
};
var jsontext = json.stringify (book);

This example usesjson.stringify () serializes a JavaScript object into a JSON string, and then protect it
exists in the variable jsontext. By default, the JSON string for the json.stringify () output does not contain any space characters or
Indentation, so the string 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. Additionally, the value is
Any attributes of undefined are also 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, use the following code
You can create an object similar to book:
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 to serialize, both
A parameter is used to specify that the JavaScript object is serialized in a different way. The first parameter is a filter, which can be an array, or it can be
to be a function; The second argument is an option that indicates whether indentation is preserved in the JSON string. Use these two individually or in combination
parameter, you can 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.
Example of a polygon.
var book = {
"title": "Professional JavaScript",
"Authors": [
"Nicholas C. Zakas"
],
Edition:3,
year:2011
};
var jsontext = json.stringify (book, ["title", "edition"]);
Jsonstringifyexample01.htm
The second argument to Json.stringify () is an array that contains two strings: "title" and "edition".it
The two attributes 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. Root
The property (key) name lets you know what to do with 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 a

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

var book = {
"title": "Professional JavaScript",
"Authors": ["Nicholas C. Zakas", "xxxx.xxx"],
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;
}
});

console.log (jsontext); // {"title": "Professional JavaScript", "Authors": "Nicholas C. Zakas,xxxx.xxx", "year" : The


Here, the function filter determines the result based on the key passed in. If the key is "authors", the array is concatenated into 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
Once this function filter is called, the passed-in key is an empty string, and the value is the book object. Serialized JSON String
As shown below:
{"title": "Professional JavaScript", "Authors": "Nicholas C. Zakas", "Year": 5000}
Each object in the object to be serialized is passed through a filter, so each object in the array with these attributes is filtered
After that, each object will only contain the "title", "Authors", and "year" properties.
Firefox 3.5 and 3.6 have a bug in the implementation of Json.stringify (), when the function is used as the second parameter of the method
This bug will appear, that is, this function can only be used as a filter: returning undefined means skipping a property and returning its
Any of his values will contain the corresponding attributes 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 number
Value, which represents the number of spaces that are indented for 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);
Jsonstringifyexample03.htm
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. Just
The value of the parameter passed into a valid control indentation, and the resulting string will contain a newline character. (It's not very meaningful to just shrink and not wrap.) ) Maximum indent null
The number of cells is 10, and all values greater than 10 are automatically converted to 10.
If the indent parameter is a string other than a numeric value, the string is used as the indent character in the JSON string (no longer makes the
With a space). 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
Character.
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 an object, returning its own JSON data format.the native Date object has a ToJSON () method,
The ability to automatically convert a JavaScript date object to an ISO 8601 date string (with a call to Toisostring () on a Date object)
The result is exactly the same).You can add the ToJSON () method to any objectLike what:

 var book = {
    "title": "Professional JavaScript",
    "authors": ["Nicholas C. Zakas "],
    Edition:3,
    year:2011,
    tojson:function () {
    &NBSP ;   return this.title;
   }
};
var jsontext = json.stringify (book);
Console.log (Jsontext);//"Professional JavaScript"


The above code defines a ToJSON () method on the book object that returns the title of the books. Like the Date object, the
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 properly
. 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 there is a ToJSON () method and can get a valid value through it, call the method. Otherwise, the object itself is returned.
(2) If the second argument is provided, apply the 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 argument is provided, the corresponding formatting is performed.
It is important to understand that the smooth
order is either to consider defining the ToJSON () method, to consider using a function filter, or to use both.
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 actually the signatures of the two functions are the same-they all receive two arguments, a key and a value, And you need to return a
value.
If the Restore function returns undefined, the corresponding key is to be 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 Date (1)// new
};
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 above code first adds a ReleaseDate property to the book object, which holds a Date object. This one
The object is serialized into a valid JSON string, then parsed and reverted to a Date in the bookcopy.
Object. When the restore function encounters the "ReleaseDate" key, a new Date object is created based on the corresponding value. The result is
A Date object is saved in the Bookcopy.releasedate property. Because of this, it is possible to invoke this object based on
getFullYear () method.


JS and JSON interaction theory and examples

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.