js便签笔记(10) - 分享:json.js源码解读笔记

1. 如何理解“json”

首先应该意识到,json是一种数据转换格式,既然是个“格式”,就是个抽象的东西。它不是js对象,也不是字符串,它只是一种格式,一种规定而已。

这个格式规定了如何将js对象转换成字符串、以及转换成怎样的字符串——序列化 —— JSON.stringify 接口;

以及如何将一个有效字符串转换成js对象——反序列化—— JSON.parse 接口;

 

2. 关于作者

json作者是 道格拉斯.克劳福德 ,是一位js大牛,写过一本《javascript语言精粹》,相信不少朋友都看过。短短200页书,果然写出了“精粹”。

 

3. 浏览器支持

W3C已经将json接口定义到标准中,目前主流浏览器也都默认支持json接口。但是还有不少IE6用户,可得小心。我曾经遇到过这样的bug。

 

4. valueOf() 的用法

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

如上代码,通过valueOf()方法,可以将一个(Number/String/Boolean)对象,转换成其对应的基本类型。

在json.stringify方法中,如果遇到一个属性值的类型是object时,首先要排除 new Number/String/Boolean(...) 这三种情况,它就是通过valueOf来操作的。

 

5. 对特殊字符的处理

json.js源码中考虑了一些无意义的unicode字符,并且对他们进行了自定义的处理。相关的正则表达式如下:

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;

这两个正则表达式,分别用在stringify和parse方法中。可以用图形形象表达这两个正则的内容,如下图:

因此,解读json.js源码,还必须了解unicode字符集的基础知识。

 

6. 在遇到Date类型或者Number类型时,都不要忘记用 isFinite()来验证有效性。

 

7. JSON.parse() 对传入字符串的验证

大家用JSON.parse(),而不直接用eval()的原因,就是因为前者是安全转换。那么这里的“安全”是通过什么来保障的呢?

源码中通过四步验证来保证。下面是这四步验证,以及我写的注释:

// 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. 将反斜线格式变为“@”,如把'\\n'变为'@'
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // 02. 将简单值替换为“]”
            // replace all simple value tokens with ']' characters. Third, we delete all    // 03. 将“: [”、“, [”替换为空字符串
            // open brackets that follow a colon or comma or that begin the text. Finally,  // 04. 看剩下的字符串是否只是 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.     // 如果是这样,那么text就可以安全的被执行eval()函数

            if (/^[\],:{}\s]*$/       //只包含 whitespace or ']' or ',' or ':' or '{' or '}'
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')  // 例如:'\\n'->'@','\\u4e00'-> '@',而'\n','\u4e00'则不变
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')   // 将 "abc"、true、false、null、数字,替换成“]”
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {...}

 

8. JSON.stringify(value, replacer, space) 第二个参数可以传伪数组

大家可能知道第二个参数replacer可以传入function或者Array,但是它也可以传如一个伪数组,模拟传入Array的情况。伪数组要这样写:

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

不过注意!浏览器中自带的JSON接口,不一定支持,例如chrome中就不识别。所以这里要谨慎使用。安全期间还是用标准的Array好一些。

 

9. 两个JS基础知识

第一,value 是数组时,注意 Object.prototype.toString.apply(value) 和 value.toString() 的区别;

第二,在 for ... in 循环中,要判断 Object.prototype.hasOwnProperty.call(value, k)

不解释,看不明白的需要去翻书。

 

10. 总结

以上是我在解读json2.js源码过程中做的一点随意的笔记,列出来跟大家分享。最后贴出我录制的json.js源码解读教程,欢迎去看看!

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

json2.js源码解读教程

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值