JSON Learning Notes

Source: Internet
Author: User
Tags tojson javascript array

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript, with a completely language-independent text format. These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (typically used to improve network transfer rates).


The syntax of JSON can represent three types of values:

    • Simple values: Using the same syntax as JavaScript, you can represent strings, numeric values, Booleans, and nulls in JSON, but do not support special value undefined in JavaScript.
    • Object: An object is a complex data structure that represents an unordered key-value pair. The values in each key-value pair can be simple values, or they can be values of complex data types.
    • Array: An array is a complex data structure that represents a list of ordered values that can be accessed by a numeric index. The value of an array can be any type-a simple value, an object, or an array.

The following three types are described in detail below:

1), Simple value:

Numeric representation: 5

String representation: "Hello world!"

The biggest difference between a JSON string and a JavaScript string is that the JSON string must use double quotation marks (single quotation marks will cause a syntax error).

2), object:

To compare the description with a JavaScript object, here is the object literal in a javascript:

var man = {      "Mcbye",      +};

In JSON, this object literal must be written as:

{      "name": "Mcbye",      "age":

You can see three differences:

      • There is no declaration of variables, because there is no concept of variables in JSON;
      • There is no semicolon at the end, because it is not a JavaScript statement and does not require semicolons;
      • The properties of the object must be enclosed in double quotation marks.

3), array:

The JSON array takes the form of an array literal in JavaScript. Examples are as follows:

JavaScript array literal: var man = ["Mcbye", +, "PKU", true];

The same array of numbers represented in JSON: ["Mcbye", "PKU", true]

As you can see, the JSON array also has no variables and semicolons.

Combining arrays and objects can make for more complex collections of data, such as the JSON array above, which can be expanded to the following:

[   [
"Name": "Mcbye", "age": +,   "College": [       "PKU",         "EECs" ] ],
"Name": "King",
"Age": 20,
2. Parsing and serialization:

One of the important reasons JSON is popular is that JSON data structures can be parsed in two directions with JavaScript objects.

The early JSON parser was basically the eval () function using JavaScript. The evaluation of the JSON data structure using eval () is risky because some malicious code might be executed.

1), JSON object has two methods:

  stringify ()-- used to serialize JavaScript objects into JSON strings.

var man = {      name: "Mcbye",      age:24,
Func:function () {//nothing happens ...} };

Serialization of the above JavaScript object: var Jsonman = json.stringify (man);

By default, the JSON string for the json.stringify () output does not include any spaces or indents, so the string saved in Mancopy is:

{"Name": "Mcbye", "Age": 24}

When serializing a JavaScript object, all functions and prototype members are deliberately ignored, not reflected in the results, and any properties with a value of undefined are skipped. The result is ultimately an instance property of a JSON data type with a value of valid.

Parse ()-- used to parse a JSON string into a JavaScript object.

var mancopy = Json.parse (Jsonman);

Man and mancopy two objects, except JSON intentionally ignored properties and functions, the other properties are the same, but even without these ignored properties and functions, man and Mancopy are completely independent, not related to the two objects.

2), serialization options:

In the actual use of the stringify () function, in addition to the JavaScript object to be serialized, you can add two additional parameters, which are used to specify a different way to serialize the JavaScript object. 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.

A, filter results:

If the filter parameter is an array, only the properties listed in the array are included in the result of Stringify (). Or in the example above:

var man = {      name: "Mcbye",      age:24,
Skills: "Javascript",
var jsontext = Json.stringify (man, ["name", "skills"]);

The value of Jsontext above should be a string containing only "name", "Skills" two properties:

{"Name": "Mcbye", "Skills": "Javascript"}

If the second argument is a function, the passed-in function accepts two parameters, the property name, and the property value. You can know how to serialize properties in an object, depending on the property name. To change the result of a serialized object, the value returned by the function is the value of the corresponding property. Note that if the function returns undefined, the corresponding property is ignored.

var man = {      name: "Mcbye",      age:24,
Skills: "Javascript",
var jsontext = json.stringify (man, Function (key, value) {
Switch (key): {
Case "Name":
return "King";
Case ' age ':
Return "secret";
return value;

After this function filter, the result of the serialized JSON string is:

{"Name": "King", "Age": "Secret", "Skills": "Javascript"}

B, 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. And, as long as a valid control indentation of the parameter value result string will contain a newline character, this is a more humane setting, but the maximum indentation of 10, more than 10 will automatically convert to 10.

C, ToJSON () method:

Defines the Tojson method for an object, which can return its own JSON data format. You can add the Tojson () method to any object. For example:

var man = {      name: "Mcbye",      age:24,
Skills: "Javascript",
Tojson:function ({return this.name;})
var jsontext = json.stringify (man);

The string saved in Jsontext after the above code execution is "Mcbye".

ToJSON () can be supplemented as a function filter, so it is important to understand the internal order of serialization. The order of serializing an object is as follows:

      1. The method is called if the Tojson () method is present and can be used to obtain a valid value. 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 in the 1th step;
      3. The corresponding serialization of each value returned by the 2nd step;
      4. If a third argument is provided, the corresponding formatting is performed.


Reference: "Professional Javascript for Web developers", Nicholas C.zakas

JSON Learning Notes

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.