Share: Json2.js Source code 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 a JS object into 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 now the mainstream browser supports the JSON interface by default. But there are a lot of IE6 users, you have to be careful. I have encountered this bug before.

4. How to use ValueOf ()

var n1 = 10;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, assuming that the type of an attribute value is an object, the first thing to do is to exclude the new Number/string/boolean (...) three cases, which are operated by valueof.

5. Handling of special characters

Some meaningless Unicode characters are considered in the Json.js source code, and they are handled in their own definition. The relevant regular forms 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. The ability to express these two regular content graphically, for example by:

Therefore, it is important to understand the basics of the Unicode character set when interpreting the Json.js source code.

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 () instead of using eval () directly is that the former is a safe conversion. So what does the "security" here guarantee?

source code with four-step verification Guarantee. Here are the four-step verification, as well as the gaze 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 see that the remaining characters is Only whitespace or '] ' or//', ' or ': ' or ' {' or '} '.     If that's so and then the text was safe for Eval.                     If so, then text is safe to run the eval () function if (/^[\],:{}\s]*$///only includes whitespace or ') ' or ', ' or ': ' or ' {' or '} ' . Test (Text.replace (/\\ (?: ["\\\/bfnrt]|u[0-9a-fa-f]{4})/g, ' @ ')//For example: ' \\n ', ' @ ', ' \\u4eXX '--' @ ', and ' \ n ', ' \u4e00 ' is unchanged. 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 parameter can pass a pseudo-array

You might 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  }

Just pay attention! The JSON interface that comes with the browser does not necessarily support it, for example, it is not recognized in Chrome. So use it carefully 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 infer Object.prototype.hasOwnProperty.call (value, K)

Do not explain, see unclear need to go through the book.

10. Summary

The above is my interpretation of Json2.js source code in the process of doing a bit of arbitrary notes, listed to share with you. Ad time:

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

json2.js Source Code Interpretation tutorial
PetShop4.0 Source Code Interpretation

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

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.