首页 > 代码库 > json.js

json.js

 由于json官网被强,现保存源码一份以备不时之需,直接保存成js文件即可。

 

  1 /*  2     json.js  3     2007-08-05  4   5     Public Domain  6   7     This file adds these methods to JavaScript:  8   9         array.toJSONString() 10         boolean.toJSONString() 11         date.toJSONString() 12         number.toJSONString() 13         object.toJSONString() 14         string.toJSONString() 15             These methods produce a JSON text from a JavaScript value. 16             It must not contain any cyclical references. Illegal values 17             will be excluded. 18  19             The default conversion for dates is to an ISO string. You can 20             add a toJSONString method to any date object to get a different 21             representation. 22  23         string.parseJSON(filter) 24             This method parses a JSON text to produce an object or 25             array. It can throw a SyntaxError exception. 26  27             The optional filter parameter is a function which can filter and 28             transform the results. It receives each of the keys and values, and 29             its return value is used instead of the original value. If it 30             returns what it received, then structure is not modified. If it 31             returns undefined then the member is deleted. 32  33             Example: 34  35             // Parse the text. If a key contains the string ‘date‘ then 36             // convert the value to a date. 37  38             myData = http://www.mamicode.com/text.parseJSON(function (key, value) {> 39                 return key.indexOf(‘date‘) >= 0 ? new Date(value) : value; 40             }); 41  42     It is expected that these methods will formally become part of the 43     JavaScript Programming Language in the Fourth Edition of the 44     ECMAScript standard in 2008. 45  46     This file will break programs with improper for..in loops. See 47     http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ 48  49     This is a reference implementation. You are free to copy, modify, or 50     redistribute. 51  52     Use your own copy. It is extremely unwise to load untrusted third party 53     code into your pages. 54 */ 55  56 /*jslint evil: true */ 57  58 // Augment the basic prototypes if they have not already been augmented. 59  60 if (!Object.prototype.toJSONString) { 61  62     Array.prototype.toJSONString = function () { 63         var a = [],     // The array holding the partial texts. 64             i,          // Loop counter. 65             l = this.length, 66             v;          // The value to be stringified. 67  68  69 // For each value in this array... 70  71         for (i = 0; i < l; i += 1) { 72             v = this[i]; 73             switch (typeof v) { 74             case ‘object‘: 75  76 // Serialize a JavaScript object value. Ignore objects thats lack the 77 // toJSONString method. Due to a specification error in ECMAScript, 78 // typeof null is ‘object‘, so watch out for that case. 79  80                 if (v) { 81                     if (typeof v.toJSONString === ‘function‘) { 82                         a.push(v.toJSONString()); 83                     } 84                 } else { 85                     a.push(‘null‘); 86                 } 87                 break; 88  89             case ‘string‘: 90             case ‘number‘: 91             case ‘boolean‘: 92                 a.push(v.toJSONString()); 93  94 // Values without a JSON representation are ignored. 95  96             } 97         } 98  99 // Join all of the member texts together and wrap them in brackets.100 101         return ‘[‘ + a.join(‘,‘) + ‘]‘;102     };103 104 105     Boolean.prototype.toJSONString = function () {106         return String(this);107     };108 109 110     Date.prototype.toJSONString = function () {111 112 // Eventually, this method will be based on the date.toISOString method.113 114         function f(n) {115 116 // Format integers to have at least two digits.117 118             return n < 10 ? ‘0‘ + n : n;119         }120 121         return ‘"‘ + this.getUTCFullYear() + ‘-‘ +122                 f(this.getUTCMonth() + 1) + ‘-‘ +123                 f(this.getUTCDate()) + ‘T‘ +124                 f(this.getUTCHours()) + ‘:‘ +125                 f(this.getUTCMinutes()) + ‘:‘ +126                 f(this.getUTCSeconds()) + ‘Z"‘;127     };128 129 130     Number.prototype.toJSONString = function () {131 132 // JSON numbers must be finite. Encode non-finite numbers as null.133 134         return isFinite(this) ? String(this) : ‘null‘;135     };136 137 138     Object.prototype.toJSONString = function () {139         var a = [],     // The array holding the partial texts.140             k,          // The current key.141             v;          // The current value.142 143 // Iterate through all of the keys in the object, ignoring the proto chain144 // and keys that are not strings.145 146         for (k in this) {147             if (typeof k === ‘string‘ &&148                     Object.prototype.hasOwnProperty.apply(this, [k])) {149                 v = this[k];150                 switch (typeof v) {151                  case ‘object‘: if (v == this) continue; 152 // Serialize a JavaScript object value. Ignore objects that lack the153 // toJSONString method. Due to a specification error in ECMAScript,154 // typeof null is ‘object‘, so watch out for that case.155 156                     if (v) {157                         if (typeof v.toJSONString === ‘function‘) {158                             a.push(k.toJSONString() + ‘:‘ + v.toJSONString());159                         }160                     } else {161                         a.push(k.toJSONString() + ‘:null‘);162                     }163                     break;164 165                 case ‘string‘:166                 case ‘number‘:167                 case ‘boolean‘:168                     a.push(k.toJSONString() + ‘:‘ + v.toJSONString());169 170 // Values without a JSON representation are ignored.171 172                 }173             }174         }175 176 // Join all of the member texts together and wrap them in braces.177 178         return ‘{‘ + a.join(‘,‘) + ‘}‘;179     };180 181 182     (function (s) {183 184 // Augment String.prototype. We do this in an immediate anonymous function to185 // avoid defining global variables.186 187 // m is a table of character substitutions.188 189         var m = {190             ‘\b‘: ‘\\b‘,191             ‘\t‘: ‘\\t‘,192             ‘\n‘: ‘\\n‘,193             ‘\f‘: ‘\\f‘,194             ‘\r‘: ‘\\r‘,195             ‘"‘ : ‘\\"‘,196             ‘\\‘: ‘\\\\‘197         };198 199 200         s.parseJSON = function (filter) {201             var j;202 203             function walk(k, v) {204                 var i;205                 if (v && typeof v === ‘object‘) {206                     for (i in v) {207                         if (Object.prototype.hasOwnProperty.apply(v, [i])) {208                             v[i] = walk(i, v[i]);209                         }210                     }211                 }212                 return filter(k, v);213             }214 215 216 // Parsing happens in three stages. In the first stage, we run the text against217 // a regular expression which looks for non-JSON characters. We are especially218 // concerned with ‘()‘ and ‘new‘ because they can cause invocation, and ‘=‘219 // because it can cause mutation. But just to be safe, we will reject all220 // unexpected characters.221 222 // We split the first stage into 3 regexp operations in order to work around223 // crippling deficiencies in Safari‘s regexp engine. First we replace all224 // backslash pairs with ‘@‘ (a non-JSON character). Second we delete all of225 // the string literals. Third, we look to see if only JSON characters226 // remain. If so, then the text is safe for eval.227 228             if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(this.229                     replace(/\\./g, ‘@‘).230                     replace(/"[^"\\\n\r]*"/g, ‘‘))) {231 232 // In the second stage we use the eval function to compile the text into a233 // JavaScript structure. The ‘{‘ operator is subject to a syntactic ambiguity234 // in JavaScript: it can begin a block or an object literal. We wrap the text235 // in parens to eliminate the ambiguity.236 237                 j = eval(‘(‘ + this + ‘)‘);238 239 // In the optional third stage, we recursively walk the new structure, passing240 // each name/value pair to a filter function for possible transformation.241 242                 return typeof filter === ‘function‘ ? walk(‘‘, j) : j;243             }244 245 // If the text is not JSON parseable, then a SyntaxError is thrown.246 247             throw new SyntaxError(‘parseJSON‘);248         };249 250 251         s.toJSONString = function () {252 253 // If the string contains no control characters, no quote characters, and no254 // backslash characters, then we can simply slap some quotes around it.255 // Otherwise we must also replace the offending characters with safe256 // sequences.257 258             if (/["\\\x00-\x1f]/.test(this)) {259                 return ‘"‘ + this.replace(/[\x00-\x1f\\"]/g, function (a) {260                     var c = m[a];261                     if (c) {262                         return c;263                     }264                     c = a.charCodeAt();265                     return ‘\\u00‘ +266                         Math.floor(c / 16).toString(16) +267                         (c % 16).toString(16);268                 }) + ‘"‘;269             }270             return ‘"‘ + this + ‘"‘;271         };272     })(String.prototype);273 }

 

json.js