File indexing completed on 2025-05-04 05:29:39

0001 /*
0002     json2.js
0003     2012-10-08
0004 
0005     Public Domain.
0006 
0007     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
0008 
0009     See http://www.JSON.org/js.html
0010 
0011 
0012     This code should be minified before deployment.
0013     See http://javascript.crockford.com/jsmin.html
0014 
0015     USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
0016     NOT CONTROL.
0017 
0018 
0019     This file creates a global JSON object containing two methods: stringify
0020     and parse.
0021 
0022         JSON.stringify(value, replacer, space)
0023             value       any JavaScript value, usually an object or array.
0024 
0025             replacer    an optional parameter that determines how object
0026                         values are stringified for objects. It can be a
0027                         function or an array of strings.
0028 
0029             space       an optional parameter that specifies the indentation
0030                         of nested structures. If it is omitted, the text will
0031                         be packed without extra whitespace. If it is a number,
0032                         it will specify the number of spaces to indent at each
0033                         level. If it is a string (such as '\t' or ' '),
0034                         it contains the characters used to indent at each level.
0035 
0036             This method produces a JSON text from a JavaScript value.
0037 
0038             When an object value is found, if the object contains a toJSON
0039             method, its toJSON method will be called and the result will be
0040             stringified. A toJSON method does not serialize: it returns the
0041             value represented by the name/value pair that should be serialized,
0042             or undefined if nothing should be serialized. The toJSON method
0043             will be passed the key associated with the value, and this will be
0044             bound to the value
0045 
0046             For example, this would serialize Dates as ISO strings.
0047 
0048                 Date.prototype.toJSON = function (key) {
0049                     function f(n) {
0050                         // Format integers to have at least two digits.
0051                         return n < 10 ? '0' + n : n;
0052                     }
0053 
0054                     return this.getUTCFullYear()   + '-' +
0055                          f(this.getUTCMonth() + 1) + '-' +
0056                          f(this.getUTCDate())      + 'T' +
0057                          f(this.getUTCHours())     + ':' +
0058                          f(this.getUTCMinutes())   + ':' +
0059                          f(this.getUTCSeconds())   + 'Z';
0060                 };
0061 
0062             You can provide an optional replacer method. It will be passed the
0063             key and value of each member, with this bound to the containing
0064             object. The value that is returned from your method will be
0065             serialized. If your method returns undefined, then the member will
0066             be excluded from the serialization.
0067 
0068             If the replacer parameter is an array of strings, then it will be
0069             used to select the members to be serialized. It filters the results
0070             such that only members with keys listed in the replacer array are
0071             stringified.
0072 
0073             Values that do not have JSON representations, such as undefined or
0074             functions, will not be serialized. Such values in objects will be
0075             dropped; in arrays they will be replaced with null. You can use
0076             a replacer function to replace those with JSON values.
0077             JSON.stringify(undefined) returns undefined.
0078 
0079             The optional space parameter produces a stringification of the
0080             value that is filled with line breaks and indentation to make it
0081             easier to read.
0082 
0083             If the space parameter is a non-empty string, then that string will
0084             be used for indentation. If the space parameter is a number, then
0085             the indentation will be that many spaces.
0086 
0087             Example:
0088 
0089             text = JSON.stringify(['e', {pluribus: 'unum'}]);
0090             // text is '["e",{"pluribus":"unum"}]'
0091 
0092 
0093             text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
0094             // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
0095 
0096             text = JSON.stringify([new Date()], function (key, value) {
0097                 return this[key] instanceof Date ?
0098                     'Date(' + this[key] + ')' : value;
0099             });
0100             // text is '["Date(---current time---)"]'
0101 
0102 
0103         JSON.parse(text, reviver)
0104             This method parses a JSON text to produce an object or array.
0105             It can throw a SyntaxError exception.
0106 
0107             The optional reviver parameter is a function that can filter and
0108             transform the results. It receives each of the keys and values,
0109             and its return value is used instead of the original value.
0110             If it returns what it received, then the structure is not modified.
0111             If it returns undefined then the member is deleted.
0112 
0113             Example:
0114 
0115             // Parse the text. Values that look like ISO date strings will
0116             // be converted to Date objects.
0117 
0118             myData = JSON.parse(text, function (key, value) {
0119                 var a;
0120                 if (typeof value === 'string') {
0121                     a =
0122 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
0123                     if (a) {
0124                         return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
0125                             +a[5], +a[6]));
0126                     }
0127                 }
0128                 return value;
0129             });
0130 
0131             myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
0132                 var d;
0133                 if (typeof value === 'string' &&
0134                         value.slice(0, 5) === 'Date(' &&
0135                         value.slice(-1) === ')') {
0136                     d = new Date(value.slice(5, -1));
0137                     if (d) {
0138                         return d;
0139                     }
0140                 }
0141                 return value;
0142             });
0143 
0144 
0145     This is a reference implementation. You are free to copy, modify, or
0146     redistribute.
0147 */
0148 
0149 /*jslint evil: true, regexp: true */
0150 
0151 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
0152     call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
0153     getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
0154     lastIndex, length, parse, prototype, push, replace, slice, stringify,
0155     test, toJSON, toString, valueOf
0156 */
0157 
0158 
0159 // Create a JSON object only if one does not already exist. We create the
0160 // methods in a closure to avoid creating global variables.
0161 
0162 if (typeof JSON !== 'object') {
0163     JSON = {};
0164 }
0165 
0166 (function () {
0167     'use strict';
0168 
0169     function f(n) {
0170         // Format integers to have at least two digits.
0171         return n < 10 ? '0' + n : n;
0172     }
0173 
0174     if (typeof Date.prototype.toJSON !== 'function') {
0175 
0176         Date.prototype.toJSON = function (key) {
0177 
0178             return isFinite(this.valueOf())
0179                 ? this.getUTCFullYear() + '-' +
0180                     f(this.getUTCMonth() + 1) + '-' +
0181                     f(this.getUTCDate()) + 'T' +
0182                     f(this.getUTCHours()) + ':' +
0183                     f(this.getUTCMinutes()) + ':' +
0184                     f(this.getUTCSeconds()) + 'Z'
0185                 : null;
0186         };
0187 
0188         String.prototype.toJSON =
0189             Number.prototype.toJSON =
0190             Boolean.prototype.toJSON = function (key) {
0191                 return this.valueOf();
0192             };
0193     }
0194 
0195     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
0196         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
0197         gap,
0198         indent,
0199         meta = {    // table of character substitutions
0200             '\b': '\\b',
0201             '\t': '\\t',
0202             '\n': '\\n',
0203             '\f': '\\f',
0204             '\r': '\\r',
0205             '"': '\\"',
0206             '\\': '\\\\'
0207         },
0208         rep;
0209 
0210 
0211     function quote(string) {
0212 
0213         // If the string contains no control characters, no quote characters, and no
0214         // backslash characters, then we can safely slap some quotes around it.
0215         // Otherwise we must also replace the offending characters with safe escape
0216         // sequences.
0217 
0218         escapable.lastIndex = 0;
0219         return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
0220             var c = meta[a];
0221             return typeof c === 'string'
0222                 ? c
0223                 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
0224         }) + '"' : '"' + string + '"';
0225     }
0226 
0227 
0228     function str(key, holder) {
0229 
0230         // Produce a string from holder[key].
0231 
0232         var i,          // The loop counter.
0233             k,          // The member key.
0234             v,          // The member value.
0235             length,
0236             mind = gap,
0237             partial,
0238             value = holder[key];
0239 
0240         // If the value has a toJSON method, call it to obtain a replacement value.
0241 
0242         if (value && typeof value === 'object' &&
0243                 typeof value.toJSON === 'function') {
0244             value = value.toJSON(key);
0245         }
0246 
0247         // If we were called with a replacer function, then call the replacer to
0248         // obtain a replacement value.
0249 
0250         if (typeof rep === 'function') {
0251             value = rep.call(holder, key, value);
0252         }
0253 
0254         // What happens next depends on the value's type.
0255 
0256         switch (typeof value) {
0257             case 'string':
0258                 return quote(value);
0259 
0260             case 'number':
0261 
0262                 // JSON numbers must be finite. Encode non-finite numbers as null.
0263 
0264                 return isFinite(value) ? String(value) : 'null';
0265 
0266             case 'boolean':
0267             case 'null':
0268 
0269                 // If the value is a boolean or null, convert it to a string. Note:
0270                 // typeof null does not produce 'null'. The case is included here in
0271                 // the remote chance that this gets fixed someday.
0272 
0273                 return String(value);
0274 
0275                 // If the type is 'object', we might be dealing with an object or an array or
0276                 // null.
0277 
0278             case 'object':
0279 
0280                 // Due to a specification blunder in ECMAScript, typeof null is 'object',
0281                 // so watch out for that case.
0282 
0283                 if (!value) {
0284                     return 'null';
0285                 }
0286 
0287                 // Make an array to hold the partial results of stringifying this object value.
0288 
0289                 gap += indent;
0290                 partial = [];
0291 
0292                 // Is the value an array?
0293 
0294                 if (Object.prototype.toString.apply(value) === '[object Array]') {
0295 
0296                     // The value is an array. Stringify every element. Use null as a placeholder
0297                     // for non-JSON values.
0298 
0299                     length = value.length;
0300                     for (i = 0; i < length; i += 1) {
0301                         partial[i] = str(i, value) || 'null';
0302                     }
0303 
0304                     // Join all of the elements together, separated with commas, and wrap them in
0305                     // brackets.
0306 
0307                     v = partial.length === 0
0308                         ? '[]'
0309                         : gap
0310                         ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
0311                         : '[' + partial.join(',') + ']';
0312                     gap = mind;
0313                     return v;
0314                 }
0315 
0316                 // If the replacer is an array, use it to select the members to be stringified.
0317 
0318                 if (rep && typeof rep === 'object') {
0319                     length = rep.length;
0320                     for (i = 0; i < length; i += 1) {
0321                         if (typeof rep[i] === 'string') {
0322                             k = rep[i];
0323                             v = str(k, value);
0324                             if (v) {
0325                                 partial.push(quote(k) + (gap ? ': ' : ':') + v);
0326                             }
0327                         }
0328                     }
0329                 } else {
0330 
0331                     // Otherwise, iterate through all of the keys in the object.
0332 
0333                     for (k in value) {
0334                         if (Object.prototype.hasOwnProperty.call(value, k)) {
0335                             v = str(k, value);
0336                             if (v) {
0337                                 partial.push(quote(k) + (gap ? ': ' : ':') + v);
0338                             }
0339                         }
0340                     }
0341                 }
0342 
0343                 // Join all of the member texts together, separated with commas,
0344                 // and wrap them in braces.
0345 
0346                 v = partial.length === 0
0347                     ? '{}'
0348                     : gap
0349                     ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
0350                     : '{' + partial.join(',') + '}';
0351                 gap = mind;
0352                 return v;
0353         }
0354     }
0355 
0356     // If the JSON object does not yet have a stringify method, give it one.
0357 
0358     if (typeof JSON.stringify !== 'function') {
0359         JSON.stringify = function (value, replacer, space) {
0360 
0361             // The stringify method takes a value and an optional replacer, and an optional
0362             // space parameter, and returns a JSON text. The replacer can be a function
0363             // that can replace values, or an array of strings that will select the keys.
0364             // A default replacer method can be provided. Use of the space parameter can
0365             // produce text that is more easily readable.
0366 
0367             var i;
0368             gap = '';
0369             indent = '';
0370 
0371             // If the space parameter is a number, make an indent string containing that
0372             // many spaces.
0373 
0374             if (typeof space === 'number') {
0375                 for (i = 0; i < space; i += 1) {
0376                     indent += ' ';
0377                 }
0378 
0379                 // If the space parameter is a string, it will be used as the indent string.
0380 
0381             } else if (typeof space === 'string') {
0382                 indent = space;
0383             }
0384 
0385             // If there is a replacer, it must be a function or an array.
0386             // Otherwise, throw an error.
0387 
0388             rep = replacer;
0389             if (replacer && typeof replacer !== 'function' &&
0390                     (typeof replacer !== 'object' ||
0391                     typeof replacer.length !== 'number')) {
0392                 throw new Error('JSON.stringify');
0393             }
0394 
0395             // Make a fake root object containing our value under the key of ''.
0396             // Return the result of stringifying the value.
0397 
0398             return str('', { '': value });
0399         };
0400     }
0401 
0402 
0403     // If the JSON object does not yet have a parse method, give it one.
0404 
0405     if (typeof JSON.parse !== 'function') {
0406         JSON.parse = function (text, reviver) {
0407 
0408             // The parse method takes a text and an optional reviver function, and returns
0409             // a JavaScript value if the text is a valid JSON text.
0410 
0411             var j;
0412 
0413             function walk(holder, key) {
0414 
0415                 // The walk method is used to recursively walk the resulting structure so
0416                 // that modifications can be made.
0417 
0418                 var k, v, value = holder[key];
0419                 if (value && typeof value === 'object') {
0420                     for (k in value) {
0421                         if (Object.prototype.hasOwnProperty.call(value, k)) {
0422                             v = walk(value, k);
0423                             if (v !== undefined) {
0424                                 value[k] = v;
0425                             } else {
0426                                 delete value[k];
0427                             }
0428                         }
0429                     }
0430                 }
0431                 return reviver.call(holder, key, value);
0432             }
0433 
0434 
0435             // Parsing happens in four stages. In the first stage, we replace certain
0436             // Unicode characters with escape sequences. JavaScript handles many characters
0437             // incorrectly, either silently deleting them, or treating them as line endings.
0438 
0439             text = String(text);
0440             cx.lastIndex = 0;
0441             if (cx.test(text)) {
0442                 text = text.replace(cx, function (a) {
0443                     return '\\u' +
0444                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
0445                 });
0446             }
0447 
0448             // In the second stage, we run the text against regular expressions that look
0449             // for non-JSON patterns. We are especially concerned with '()' and 'new'
0450             // because they can cause invocation, and '=' because it can cause mutation.
0451             // But just to be safe, we want to reject all unexpected forms.
0452 
0453             // We split the second stage into 4 regexp operations in order to work around
0454             // crippling inefficiencies in IE's and Safari's regexp engines. First we
0455             // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
0456             // replace all simple value tokens with ']' characters. Third, we delete all
0457             // open brackets that follow a colon or comma or that begin the text. Finally,
0458             // we look to see that the remaining characters are only whitespace or ']' or
0459             // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
0460 
0461             if (/^[\],:{}\s]*$/
0462                     .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
0463                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
0464                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
0465 
0466                 // In the third stage we use the eval function to compile the text into a
0467                 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
0468                 // in JavaScript: it can begin a block or an object literal. We wrap the text
0469                 // in parens to eliminate the ambiguity.
0470 
0471                 j = eval('(' + text + ')');
0472 
0473                 // In the optional fourth stage, we recursively walk the new structure, passing
0474                 // each name/value pair to a reviver function for possible transformation.
0475 
0476                 return typeof reviver === 'function'
0477                     ? walk({ '': j }, '')
0478                     : j;
0479             }
0480 
0481             // If the text is not JSON parseable, then a SyntaxError is thrown.
0482 
0483             throw new SyntaxError('JSON.parse');
0484         };
0485     }
0486 }());