JS Note Notes (10)-Share: json2.js Source Interpretation notes

Source: Internet
Author: User

1. How to Understand "JSON"

The first thing you should realize is that JSON is a data conversion format, and since it's a "format," it's an abstraction. It is not a JS object, nor a string, it is just a format, a rule only.

This format specifies how to convert the JS object to a string, and the string to which it is converted-the serialized--json.stringify interface;

And how to convert a valid string into a JS object--Deserialize the--json.parse interface;

2. About the author

The JSON author is Douglas Crawford, a JS Daniel, who wrote a book on the essence of JavaScript, and I believe many friends have seen it. Just 200 pages of the book, sure enough to write a "pristine."

3. Browser support

The web has already defined the JSON interface to the standard, and the current mainstream browser also supports the JSON interface by default. But there are a lot of IE6 users, you have to be careful. I have ever encountered such a bug.

4. Use of ValueOf ()

var N1 = Ten, var n2 = new number,Console.log (typeof N1)  ; Numberconsole.log (typeof N2);  Objectconsole.log (typeof n2.valueof ());   

As the code above, through the valueof () method, A (Number/string/boolean) object can be converted to its corresponding base type.

In the Json.stringify method, if you encounter a property value whose type is object, the first thing to do is to exclude the new Number/string/boolean (...) in three cases, which is done by valueof.

5. Handling of special characters

Some meaningless Unicode characters are considered in the Json.js source code, and they are processed in a custom way. The relevant regular expressions are as follows:

escapable =/[\\\ "\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f \ufeff\ufff0-\uffff]/g;cx =/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\ u206f\ufeff\ufff0-\uffff]/g;

These two regular expressions are used in the stringify and parse methods, respectively. These two regular content can be expressed graphically, such as:

Therefore, the interpretation of the Json.js source code, you must also understand the basic knowledge of the Unicode character set.

6. Do not forget to use Isfinite () to verify validity when encountering the date type or number type.

7. Json.parse () Validation of incoming strings

The reason why everyone uses json.parse () rather than eval () is because the former is a safe conversion. So what does the "security" here guarantee?

The source code through four step verification to ensure. Here are the four-step verification, as well as the comments I wrote:

We split the second stage into 4 regexp operations in order to work around//crippling inefficiencies in IE ' s and Safari ' s regexp engines. First we//01. Change the backslash format to "@", such as ' \\n ' to ' @ '//replace the JSON backslash pairs with ' @ ' (a non-json character). Second, we//02. Replace the simple values with "]"//and replace all simply value tokens with '] ' characters. Third, we delete all//03. Replace ": [", ", [" with an empty string//open brackets that follow a colon or comma or that begin the text. Finally,//04. See if the rest of the string is just whitespace or ' ' or ', ' or ': ' or ' {' or '} '//' We look to seeing that the remaining characters is O nly whitespace or '] ' or//', ' or ': ' or ' {' or '} '.     If that's so and then the text was safe for Eval.                    If so, then the text can be safely executed by the eval () function if (/^[\],:{}\s]*$///only contains whitespace or ') ' or ', ' or ': ' or ' {' or '} ' . Test (Text.replace (/\\ (?: ["\\\/bfnrt]|u[0-9a-fa-f]{4})/g, ' @ ')///For example: ' \\n ', ' @ ', ' \\u4e00' @ ', and ' \ n ', ' \u4e00 ' is the same. Replace (/"[^" \\\n\r]* "|true|false|null|-?\d+ (?: \). \d*)? (?: [ee][+\-]?\d+)?/g, '] ')//Replace "ABC", True, false, NULL, and number with "]". Replace (/(?: ^|:|,) (?: \ s*\[) (+/g, "))) {...}

8. Json.stringify (value, replacer, space) The second argument can pass a pseudo-array

You may know that the second parameter, Replacer, can pass in a function or array, but it can also be passed as a pseudo-array, simulating the case of an incoming array. Pseudo-arrays are written like this:

{    0: ' A ',    1: ' B ',    2: ' x ',    length:3  }   

But watch out! The JSON interface that comes with the browser does not necessarily support it, for example, it is not recognized in Chrome. So use caution here. It is better to use the standard array during the security period.

9. Two JS basic knowledge

First, when value is an array, note the difference between Object.prototype.toString.apply (value) and value.tostring ();

Second, in the for ... in loop, to determine the Object.prototype.hasOwnProperty.call (value, K)

Do not explain, can not understand the need to go through the book.

10. Summary

The above is my interpretation of Json2.js source code in the process of doing a little random notes, listed to share with you. Finally posted I recorded the json.js source interpretation tutorial, Welcome to see!

--------------------------------------------------------------------------

Json2.js Source Code Interpretation tutorial

---------------------------------------------------------------------------

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.