Share: Notes for interpreting json2.js source code

Source: Internet
Author: User

1. How to understand "json"

First, we should realize that json is a data conversion format. Since it is a "format", it is an abstract thing. It is neither a js object nor a string. It is just a format and a specification.

This format specifies how to convert a js object to a string, and how to convert it to a string -- serialization -- JSON. stringify interface;

And how to convert a valid string to a js object -- deserialization -- JSON. parse interface;

 

2. About the author

I believe many of my friends have read this article, written by Douglas croford, a javascript guru. In a short 200-page book, I wrote "essence ".

 

3. browser support

W3C has defined json interfaces as standard. Currently, mainstream browsers also support json interfaces by default. However, there are still many Internet Explorer 6 users, so be careful. I have encountered such a bug.

 

4. valueOf () Usage

var n1 = 10;var n2 = new Number(10);console.log(typeof n1);  //numberconsole.log(typeof n2);  //objectconsole.log(typeof n2.valueOf());  //number 

The above code converts a (Number/String/Boolean) object to its basic type through the valueOf () method.

In json. in the stringify method, if the type of an attribute value is object, you must first exclude new Number/String/Boolean (...) in these three cases, it is operated through valueOf.

 

5. Handling special characters

Some meaningless unicode characters are taken into account in the json. js source code and customized. The related 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. You can use a graphical image to express the two regular expressions, such:

Therefore, to interpret the json. js source code, you must understand the basic knowledge of the unicode Character Set.

 

6. When encountering the Date or Number type, do not forget to use isFinite () to verify the validity.

 

7. JSON. parse () Verification of input strings

The reason why JSON. parse () is used instead of eval () is that the former is a secure conversion. So what is the "security" here to ensure?

The source code is verified in four steps. The following are the four verification steps and comments I have written:

// We split the second stage into 4 regexp operations in order to work around und // crippling inefficiencies in IE's and Safari's regexp engines. first we // 01. change the backslash format to "@". For example, change '\ n' to' @ '// replace the JSON backslash pairs with' @ '(a non-JSON character ). second, we // 02. replace a simple value with "]" // replace all simple values tokens with '] 'characters. third, we delete all // 03. replace ": [", ", [" with an empty string // open bracket S that follow a colon or comma or that begin the text. finally, // 04. check whether the remaining string is whitespace or ']' or ',' or ': 'or' {'or'} '// we look to see that the remaining characters are only whitespace or'] 'or //', 'or ': 'or' {'or '}'. if that is so, then the text is safe for eval. // if this is the case, text can be safely executed by the eval () function if (/^ [\],: {} \ s] * $ // only contains whitespace or ']' or ',' or ':' or '{' or '}'. test (text. r Eplace (/\\(?: ["\\\/Bfnrt] | u [0-9a-fA-F] {4})/g, '@') // For example: '\ N'-> '@', '\ u4e00'->' @ ', while' \ n' and '\ u4e00' remain 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 be a pseudo array.

You may know that the second replacer parameter can be passed in a function or Array, but it can also be passed as a pseudo Array to simulate the input of an Array. The pseudo array should be written like this:

{    0 : 'a',    1 : 'b',    2 : 'x',    length : 3  }

But note! The JSON interface in the browser is not necessarily supported. For example, it is not recognized in chrome. Therefore, use it with caution. Standard Array is better during the security period.

 

9. Two basic JS knowledge

First, when values are arrays, note the differences between Object. prototype. toString. apply (value) and value. toString;

Second, in the for... in loop, You must judge Object. prototype. hasOwnProperty. call (value, k)

If you do not understand it, you need to read the book.

 

10. Summary

The above are some casual notes I made during the interpretation of json2.js source code, and I will share them with you. Ad Time:

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

Json2.js source code explanation tutorial
Source code explanation for PetShop4.0

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

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.