In-depth understanding of JSON

Source: Internet
Author: User
Tags tojson
Let's take a look at a common JS object serialized into a JSON string. What is the string of the following JS object after JSON. stringify? Do not rush to copy and paste it to the console. First open a code editor or paper, write and read it, and then carefully compare your console output. If there is a mistake, remember to read the full text and comment, haha. Let's take a look at a common JS object serialized into a JSON string. What is the string of the following JS object after JSON. stringify? Do not rush to copy and paste it to the console. First open a code editor or paper, write and read it, and then carefully compare your console output. If there is a mistake, remember to read the full text and comment, haha.


var friend = {
     firstName: 'Good',
     'lastName': 'Man',
     'address': undefined,
     'phone': ["1234567", undefined],
     'fullName': function () {
         return this.firstName + '' + this.lastName;
     }
};

JSON.stringify (friend); // What does this line return?

Second, if I want to convert all the 'friend' names into uppercase letters in the final JSON string, that is, "Good" to "GOOD ", how can we change "Man" to "MAN?

Based on the above two questions, let's trace the source and ask, what exactly is JSON? Why is JSON easy to exchange data? What is the difference between JSON and JS objects? JSON. parse, JSON. stringify, and uncommon toJSON in JS. What are the parameters and processing details of these functions?

Welcome to this in-depth JSON mining tour. The following describes how to understand JSON in the following aspects:

  • The first is understanding that "JSON is a lightweight data exchange format;


  • Then let's look at the differences between JSON and JS objects that are often confused;


  • Finally, let's take a look at the detailed execution details of these JSON-related functions in JS.

I hope that the full text will allow me to clearly understand what JSON is and be proficient in using JSON as I did before. without reading the console, I will know what the JS object will be output after being serialized into a JSON string.


1. JSON is a text-based format that is better than lightweight and used for data exchange.

If you have never been to the official introduction of JSON, You can go here. The first and second sections of the official introduction clearly express what JSON is and I will extract what JSON is into the following aspects:

1. A data format

What is the format? It is to regulate how your data is represented. For example, a person named "Two hundred and six", height "160cm", weight "60kg ", now you want to pass this person's information to others or other things. You have many options:

  • The name is "Two hundred and six", the height is "160cm", and the weight is "60kg"


  • Name = "Two hundred and six" & height = "160" & weight = "60 kg"


  • Two hundred and six16060


  • {"Name": "Two hundred and six", "height": 160, "weight": 60}


  • ......

All of the above options share the same data, but you can see that there are various formats. This is a variety of formatted data, and JSON is one of them.

2. text-based Data Format

JSON is a text-based data format. Compared with binary-based data, JSON is transmitted in line with the JSON format (as for what is the JSON format, we will talk about the second part) is called a "JSON string ".

3. lightweight data format

Before JSON, there is a data format named xml, which is still widely used, but JSON is more lightweight. For example, xml requires a lot of labels, as in the above example, as you can see, labels occupy a lot of space in xml data, while JSON is lightweight, that is, the same data occupies less bandwidth in JSON format, this has obvious advantages in the case of massive data requests and transmission.

4. Widely used in data exchange

Lightweight is already an advantage for data exchange, but more importantly, JSON is easy to read, write, and machine parse. That is, this JSON is user-friendly and lightweight to humans and machines, JSON is widely used for data exchange because it is text-based.

For example, if the backend PHP processes the ajax POST request in the previous JavaScript code:

  1. The front-end constructs a JS object to encapsulate the data to be transmitted, converts the JS object to a JSON string, and then sends the request to the backend;


  2. The backend PHP receives the JSON string, converts the JSON string to a PHP Object, and then processes the request.

As you can see, the same data here has three different forms: front-end JS objects, transmitted JSON strings, and backend PHP objects, javascript objects and PHP objects are obviously not one thing. However, since most people use JSON to transmit data, everyone can understand this data format, JSON data format can be easily converted into a data structure that you can understand, which facilitates data exchange in other language environments.

2. gossip between JSON and JS objects"

I often hear the phrase "JSON is a subset of JS", and I have always thought so, every JSON-formatted string can be parsed into js until it finds a strange thing...

1. Why are two essentially different things so close?

JSON and JS objects are essentially not the same thing. They are like the "zebra crossings" and "zebra crossings". The "zebra crossings" are represented and named based on the stripes on the "ZEBRA, however, the zebra is active, and the zebra line is non-biological.

Similarly, "JSON" Full name "JavaScript Object Notation", so its format (syntax) is based on JS, but it is a format, and JS Object is an instance, it is a memory thing.

To tell a joke, if the JSON is based on PHP, it may be called PON. The form may be like this ['propertyone' => 'foo ', 'propertytwo' => 42,]. If so, JSON may be close to PHP now.

In addition, JSON can be transmitted because it is in text format, but JS objects cannot be transmitted. In terms of syntax, JSON will be stricter, but JS objects will be loose.

Why are two different things so closely? Because JSON is evolved from JS after all, and the syntax is similar.

2. JSON format. Where is the syntax of JS objects strictly?

First, compare the differences between the two in the form of "key-value pairs as objects", and then list the differences in the form of JSON.

Comparison content JSON JS object

Key name

Must be double quotation marks

No quotation marks, single quotation marks, or double quotation marks are allowed.

Attribute Value

It can only be a numeric value (in decimal format), a string (double quotation marks), a Boolean value, or null,
It can also be an array or an object that meets the JSON requirements,
It cannot be a function, NaN, Infinity,-Infinity, or undefined.

What do you like

Comma

The last attribute cannot be followed by a comma.

Yes

Value

Leading 0 cannot be used. digits must be placed after the decimal point.

No restrictions

As you can see, the JSON format is more strict than that of JS objects, so most JS objects written do not conform to the JSON format.

The following code is referenced here:

var obj1 = (); // this is just a JS object

// Can be called: JSON format JavaScript object
var obj2 = {"width": 100, "height": 200, "name": "rose"};

// Call this: JSON-formatted string
var str1 = '{"width": 100, "height": 200, "name": "rose"}';

// This can be called a JSON format array, which is a slightly more complex form of JSON
var arr = [
     {"width": 100, "height": 200, "name": "rose"},
     {"width": 100, "height": 200, "name": "rose"},
     {"width": 100, "height": 200, "name": "rose"},
];

// This can be called a slightly more complicated JSON format string
var str2 = '[' +
     '{"width": 100, "height": 200, "name": "rose"},' +
     '{"width": 100, "height": 200, "name": "rose"},' +
     '{"width": 100, "height": 200, "name": "rose"},' +
']';

In addition to the common "normal" JSON format, either it is represented as an object in the form {...}, either in the form of an array [...], any separate 10-digit numeric value, double quotation mark string, Boolean value, and null are valid in JSON format.

Complete JSON syntax reference is provided here.

3. In an interesting place, JSON is not a subset of JS.

First, you can copy the following code to the console:

var code = '"\u2028\u2029"';  JSON.parse(code); // works fine  eval(code); // fails

The two characters \ u2028 and \ u2029 indicate the line separator and paragraph separator respectively. JSON. parse can be parsed normally, but an error will be reported when parsing as js.

3. What about the JSON functions in these JS?

In JS, we mainly access two JSON-related functions for conversion between JSON strings and JS data structures. One is called JSON. stringify: It's very clever. It's smart that any JS object you write that does not conform to the JSON format can help you process it into a JSON-format string, so you have to know what it actually does, lest it just be smart, and then let you Debug long time; the other is called JSON. parse is used to convert a json string to the JS data structure. It is very strict. If your JSON string is not constructed correctly, it cannot be parsed.

They have more than one parameter, although we often use it to pass in only one parameter.

In addition, there is also a toJSON function, which we rarely see, but it will affect JSON. stringify.

1. Convert the JS data structure to a JSON string -- JSON. stringify

The function signature of this function is as follows:

JSON.stringify(value[, replacer [, space]])

The following sections show ~ The usage of the three parameters is the "smart" thing it does during serialization. Pay special attention to it.

1.1 Basic use -- only one parameter is required

This is used by all users to input a JS object or array in JSON format, JSON. stringify ({"name": "Good Man", "age": 18}) returns a string "{" name ":" Good Man "," age ": 18 }".

We can see that the JS object we passed in is in JSON format, with double quotation marks and no attribute values not accepted by JSON. So how to play like in the example at the beginning? Don't worry. Let's give a simple example to illustrate the meaning of several parameters of this function, and then let's talk about this problem.

1.2 The second parameter can be a function or an array.
  • If the second parameter is a function, every attribute in the serialization process will be converted and processed by this function.


  • If the second parameter is an array, only the attributes contained in the array will be serialized to the final JSON string.


  • If the second parameter is null, there is no difference between it and null, but you do not want to set the second parameter. If you want to set the third parameter, you can set the second parameter to null.

The second parameter is a function.

var friend = {
     "firstName": "Good",
     "lastName": "Man",
     "phone": "1234567",
     "age": 18
};

var friendAfter = JSON.stringify (friend, function (key, value) {
     if (key === "phone")
         return "(000)" + value;
     else if (typeof value === "number")
         return value + 10;
     else
         return value; // If you delete the else clause, the result will be undefined
});

console.log (friendAfter);
// Output: {"firstName": "Good", "lastName": "Man", "phone": "(000) 1234567", "age": 28}

If the second parameter is set to a function, the function must return each item. This function accepts two parameters, one key name and the other a property value, the function must return a new property value for each original property value.

So the question is, what if the input is not the form of the key-Value Pair object, but the array form of square brackets ?, For example, if the above friend Becomes like this: friend = ["Jack", "Rose"], then what is the key and value received by this attribute-by-attribute processing function? If it is in the array format, the key is the index, and the value is the array item. You can print the key and value verification in this function on the console.

The second parameter is an array.

var friend = {
     "firstName": "Good",
     "lastName": "Man",
     "phone": "1234567",
     "age": 18
};

// Note that the array below has a value that is not any property name of the above object
var friendAfter = JSON.stringify (friend, ["firstName", "address", "phone"]);

console.log (friendAfter);
// {"firstName": "Good", "phone": "1234567"}
// The specified "address" was ignored because it was not found in the original object

If the second parameter is an array, only the attributes in the array will be serialized into the result string, attributes that cannot be found in the provided array will not be included. attributes that exist in the array but do not exist in the source JS object will be ignored and no error will be reported.

1.3 The third parameter is used to beautify the output-not recommended

Specifies the blank characters used for indentation. the following values can be taken:

  • It is a number ranging from 1 to 10, representing a few white spaces.


  • If it is a string, it is used to replace spaces. A maximum of the first 10 characters of the string can be used.


  • If this parameter is not provided, it is set to null, which is equal to setting a number smaller than 1.

var friend = {
    "firstName": "Good",
    "lastName": "Man",
    "phone": {"home": "1234567", "work": "7654321"}
};

// Direct conversion is like this:
// {"firstName": "Good", "lastName": "Man", "phone": {"home": "1234567", "work": "7654321"}}

var friendAfter = JSON.stringify (friend, null, 4);
console.log (friendAfter);
/ *
{
    "firstName": "Good",
    "lastName": "Man",
    "phone": {
        "home": "1234567",
        "work": "7654321"
    }
}
* /

var friendAfter = JSON.stringify (friend, null, "HAHAHAHA");
console.log (friendAfter);
/ *
{
HAHAHAHA "firstName": "Good",
HAHAHAHA "lastName": "Man",
HAHAHAHA "phone": {
HAHAHAHAHAHAHAHA "home": "1234567",
HAHAHAHAHAHAHAHA "work": "7654321"
HAHAHAHA}
}
* /

var friendAfter = JSON.stringify (friend, null, "WhatAreYouDoingNow");
console.log (friendAfter);
/ * Takes up to 10 characters
{
WhatAreYou "firstName": "Good",
WhatAreYou "lastName": "Man",
WhatAreYou "phone": {
WhatAreYouWhatAreYou "home": "1234567",
WhatAreYouWhatAreYou "work": "7654321"
WhatAreYou}
}
* /

Just smile, don't use it like this. serialization is for transmission. The smaller the transmission is, the better. It is difficult to parse it by adding inexplicable indentations (if it is a string ), it also weakens the lightweight feature ..

1.4 pay attention to the "Cleverness" of this function (important)

If there are other uncertain situations, the best way is to "Have a try", and the experiment on the console is clear.

  • If the key name is not a double quotation mark (including no or single quotation marks), it is automatically converted into double quotation marks. If the string is single quotation marks, it is automatically converted into double quotation marks.


  • The last attribute is followed by a comma and will be removed automatically.


  • Attributes of non-array objects cannot appear in serialized strings in specific order.
    This is easy to understand, that is, the attribute order of non-array objects in the final string is not guaranteed to be consistent with the original attribute order.


  • The encapsulated objects of Boolean values, numbers, and strings are automatically converted to the corresponding original values during serialization.
    That is, what new String ("bala") will become "bala", and new Number (2017) will become 2017


  • Undefined, any function (in fact, there will be a magic thing in a function, which will be discussed later) and the symbol value (For details, refer to the introduction of symbol in ES6)

    • Appear in attribute values of non-array objects: ignored during serialization


    • In the array: converted to null


JSON.stringify ({x: undefined, y: function () {return 1;}, z: Symbol ("")});
// Ignored in non-array object property values: "{}"
JSON.stringify ([undefined, Object, Symbol ("")]);
// Appears in the property value of the array object and becomes null: "[null, null, null]"
  • NaN, Infinity, and-Infinity are converted to null in array or non-array objects.


  • All the attributes with symbol as the attribute key will be completely ignored, even if the replacer parameter forcibly specifies that they contain


  • Properties that cannot be enumerated are ignored.

2. parse the JSON string into the JS Data Structure-JSON. parse

The function signature of this function is as follows:

JSON.parse(text[, reviver])

If the first parameter, that is, the JSON string is not a valid string, this function will throw an error. Therefore, if you are writing a script that returns the JSON string at the backend, it is best to call the serialized functions related to the JSON string of the language itself. If you concatenate the serialized strings, pay special attention to whether the serialized strings are legal, legal means that the JSON string is in the strict JSON format.

It is worth noting that there is an optional second parameter, which must be a function. This function serves before the property has been parsed but has not been returned, process the attributes before returning them.

var friend = {
     "firstName": "Good",
     "lastName": "Man",
     "phone": {"home": "1234567", "work": ["7654321", "999000"]}
};

// Let's serialize it first
var friendAfter = JSON.stringify (friend);
// '{"firstName": "Good", "lastName": "Man", "phone": {"home": "1234567", "work": ["7654321", "999000"]}}'

/ / Parse it out, print out the key and value in the function of the second parameter
JSON.parse (friendAfter, function (k, v) {
     console.log (k);
     console.log (v);
     console.log ("----");
});
/ *
firstName
Good
----
lastName
Man
----
home
1234567
----
0
7654321
----
1  
999000
----
work
[]
----
phone
Object
----

Object
----
* /

Taking a closer look at these outputs, we can find that the traversal is from the inside out. It may be misunderstood by the word "Inside" and "outside". The bottom layer is the two values in the internal array, however, the output starts with the first attribute. How is the output from the inside out?

This refers to composite attributes. In general, traversal is performed from start to end. For simple attribute values (values, strings, Boolean values, and null ), the traversal is completed directly. If the attribute value is in the form of an object or an array, pause and traverse the sub-JSON first. The traversal principle is also the same. After this composite attribute is traversed, then the traversal of this attribute is returned.

Essentially, this is a depth-first traversal.

Note the following two points:

  • If reviver returns undefined, the current attribute will be deleted from the object to which it belongs. If other values are returned, the returned value will become the new attribute value of the current attribute.


  • You can notice that the last set of output in the above example does not seem to have a key. In fact, this key is an empty string, and the final object is the final parsed object, there are no real attributes.

3. The magic function that affects JSON. stringify-object. toJSON

If you implement the toJSON method on a JS object, call JSON. when stringify serializes this JS object, JSON. stringify serializes the value returned by the toJSON method of this object as a parameter.

var info = {
     "msg": "I Love You",
     "toJSON": function () {
         var replaceMsg = new Object ();
         replaceMsg ["msg"] = "Go Die";
         return replaceMsg;
     }
};

JSON.stringify (info);
// It's out, and it returns: '"{" msg ":" Go Die "}"' 

This function is like this.

In fact, the Date type can be directly transmitted to JSON. stringify for parameters. The truth is that the Date type has built-in toJSON method.

Iv. Summary and compatibility issues

Here, I finally combed the JSON in JSON and JS, and traversed the details and points of attention, I know that JSON is a lightweight data exchange format derived from the JS language. I also understand the difference between JSON and the general JS data structure (especially the object, the three functions and details about JSON processing in JS are carefully discussed.

Unfortunately, the above three functions are not compatible with IE 7 and earlier browsers. For compatibility discussions, please wait. If you want to solve the compatibility problem directly on the application, you can apply the official JSON js to solve the problem.

If any, leave a message.

The above is a detailed understanding of JSON. For more information, see other related articles in the first PHP community!

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.