JAVASCRIPT   102

json2.js

Guest on 31st July 2021 07:08:59 AM

  1. /*
  2.     json2.js
  3.  
  4.     Public Domain.
  5.  
  6.     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  7.  
  8.     See http://www.JSON.org/js.html
  9.  
  10.  
  11.     This code should be minified before deployment.
  12.     See http://javascript.crockford.com/jsmin.html
  13.  
  14.     USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  15.     NOT CONTROL.
  16.  
  17.  
  18.     This file creates a global JSON object containing two methods: stringify
  19.     and parse. This file is provides the ES5 JSON capability to ES3 systems.
  20.     If a project might run on IE8 or earlier, then this file should be included.
  21.     This file does nothing on ES5 systems.
  22.  
  23.         JSON.stringify(value, replacer, space)
  24.             value       any JavaScript value, usually an object or array.
  25.  
  26.             replacer    an optional parameter that determines how object
  27.                         values are stringified for objects. It can be a
  28.                         function or an array of strings.
  29.  
  30.             space       an optional parameter that specifies the indentation
  31.                         of nested structures. If it is omitted, the text will
  32.                         be packed without extra whitespace. If it is a number,
  33.                         it will specify the number of spaces to indent at each
  34.                         level. If it is a string (such as '\t' or ' '),
  35.                         it contains the characters used to indent at each level.
  36.  
  37.             This method produces a JSON text from a JavaScript value.
  38.  
  39.             When an object value is found, if the object contains a toJSON
  40.             method, its toJSON method will be called and the result will be
  41.             stringified. A toJSON method does not serialize: it returns the
  42.             value represented by the name/value pair that should be serialized,
  43.             or undefined if nothing should be serialized. The toJSON method
  44.             will be passed the key associated with the value, and this will be
  45.             bound to the value
  46.  
  47.             For example, this would serialize Dates as ISO strings.
  48.  
  49.                 Date.prototype.toJSON = function (key) {
  50.                     function f(n) {
  51.                         // Format integers to have at least two digits.
  52.                         return n < 10
  53.                             ? '0' + n
  54.                             : n;
  55.                     }
  56.  
  57.                     return this.getUTCFullYear()   + '-' +
  58.                          f(this.getUTCMonth() + 1) + '-' +
  59.                          f(this.getUTCDate())      + 'T' +
  60.                          f(this.getUTCHours())     + ':' +
  61.                          f(this.getUTCMinutes())   + ':' +
  62.                          f(this.getUTCSeconds())   + 'Z';
  63.                 };
  64.  
  65.             You can provide an optional replacer method. It will be passed the
  66.             key and value of each member, with this bound to the containing
  67.             object. The value that is returned from your method will be
  68.             serialized. If your method returns undefined, then the member will
  69.             be excluded from the serialization.
  70.  
  71.             If the replacer parameter is an array of strings, then it will be
  72.             used to select the members to be serialized. It filters the results
  73.             such that only members with keys listed in the replacer array are
  74.             stringified.
  75.  
  76.             Values that do not have JSON representations, such as undefined or
  77.             functions, will not be serialized. Such values in objects will be
  78.             dropped; in arrays they will be replaced with null. You can use
  79.             a replacer function to replace those with JSON values.
  80.             JSON.stringify(undefined) returns undefined.
  81.  
  82.             The optional space parameter produces a stringification of the
  83.             value that is filled with line breaks and indentation to make it
  84.             easier to read.
  85.  
  86.             If the space parameter is a non-empty string, then that string will
  87.             be used for indentation. If the space parameter is a number, then
  88.             the indentation will be that many spaces.
  89.  
  90.             Example:
  91.  
  92.             text = JSON.stringify(['e', {pluribus: 'unum'}]);
  93.             // text is '["e",{"pluribus":"unum"}]'
  94.  
  95.  
  96.             text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  97.             // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  98.  
  99.             text = JSON.stringify([new Date()], function (key, value) {
  100.                 return this[key] instanceof Date
  101.                     ? 'Date(' + this[key] + ')'
  102.                     : value;
  103.             });
  104.             // text is '["Date(---current time---)"]'
  105.  
  106.  
  107.         JSON.parse(text, reviver)
  108.             This method parses a JSON text to produce an object or array.
  109.             It can throw a SyntaxError exception.
  110.  
  111.             The optional reviver parameter is a function that can filter and
  112.             transform the results. It receives each of the keys and values,
  113.             and its return value is used instead of the original value.
  114.             If it returns what it received, then the structure is not modified.
  115.             If it returns undefined then the member is deleted.
  116.  
  117.             Example:
  118.  
  119.             // Parse the text. Values that look like ISO date strings will
  120.             // be converted to Date objects.
  121.  
  122.             myData = JSON.parse(text, function (key, value) {
  123.                 var a;
  124.                 if (typeof value === 'string') {
  125.                     a =
  126. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  127.                     if (a) {
  128.                         return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  129.                             +a[5], +a[6]));
  130.                     }
  131.                 }
  132.                 return value;
  133.             });
  134.  
  135.             myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  136.                 var d;
  137.                 if (typeof value === 'string' &&
  138.                         value.slice(0, 5) === 'Date(' &&
  139.                         value.slice(-1) === ')') {
  140.                     d = new Date(value.slice(5, -1));
  141.                     if (d) {
  142.                         return d;
  143.                     }
  144.                 }
  145.                 return value;
  146.             });
  147.  
  148.  
  149.     This is a reference implementation. You are free to copy, modify, or
  150.     redistribute.
  151. */
  152.  
  153. /*jslint
  154.     eval, for, this
  155. */
  156.  
  157. /*property
  158.     JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  159.     getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  160.     lastIndex, length, parse, prototype, push, replace, slice, stringify,
  161.     test, toJSON, toString, valueOf
  162. */
  163.  
  164.  
  165. // Create a JSON object only if one does not already exist. We create the
  166. // methods in a closure to avoid creating global variables.
  167.  
  168. if (typeof JSON !== 'object') {
  169.     JSON = {};
  170. }
  171.  
  172. (function () {
  173.     'use strict';
  174.    
  175.     var rx_one = /^[\],:{}\s]*$/,
  176.         rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
  177.         rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
  178.         rx_four = /(?:^|:|,)(?:\s*\[)+/g,
  179.         rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  180.         rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  181.  
  182.     function f(n) {
  183.         // Format integers to have at least two digits.
  184.         return n < 10
  185.             ? '0' + n
  186.             : n;
  187.     }
  188.    
  189.     function this_value() {
  190.         return this.valueOf();
  191.     }
  192.  
  193.     if (typeof Date.prototype.toJSON !== 'function') {
  194.  
  195.         Date.prototype.toJSON = function () {
  196.  
  197.             return isFinite(this.valueOf())
  198.                 ? this.getUTCFullYear() + '-' +
  199.                         f(this.getUTCMonth() + 1) + '-' +
  200.                         f(this.getUTCDate()) + 'T' +
  201.                         f(this.getUTCHours()) + ':' +
  202.                         f(this.getUTCMinutes()) + ':' +
  203.                         f(this.getUTCSeconds()) + 'Z'
  204.                 : null;
  205.         };
  206.  
  207.         Boolean.prototype.toJSON = this_value;
  208.         Number.prototype.toJSON = this_value;
  209.         String.prototype.toJSON = this_value;
  210.     }
  211.  
  212.     var gap,
  213.         indent,
  214.         meta,
  215.         rep;
  216.  
  217.  
  218.     function quote(string) {
  219.  
  220. // If the string contains no control characters, no quote characters, and no
  221. // backslash characters, then we can safely slap some quotes around it.
  222. // Otherwise we must also replace the offending characters with safe escape
  223. // sequences.
  224.  
  225.         rx_escapable.lastIndex = 0;
  226.         return rx_escapable.test(string)
  227.             ? '"' + string.replace(rx_escapable, function (a) {
  228.                 var c = meta[a];
  229.                 return typeof c === 'string'
  230.                     ? c
  231.                     : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  232.             }) + '"'
  233.             : '"' + string + '"';
  234.     }
  235.  
  236.  
  237.     function str(key, holder) {
  238.  
  239. // Produce a string from holder[key].
  240.  
  241.         var i,          // The loop counter.
  242.             k,          // The member key.
  243.             v,          // The member value.
  244.             length,
  245.             mind = gap,
  246.             partial,
  247.             value = holder[key];
  248.  
  249. // If the value has a toJSON method, call it to obtain a replacement value.
  250.  
  251.         if (value && typeof value === 'object' &&
  252.                 typeof value.toJSON === 'function') {
  253.             value = value.toJSON(key);
  254.         }
  255.  
  256. // If we were called with a replacer function, then call the replacer to
  257. // obtain a replacement value.
  258.  
  259.         if (typeof rep === 'function') {
  260.             value = rep.call(holder, key, value);
  261.         }
  262.  
  263. // What happens next depends on the value's type.
  264.  
  265.         switch (typeof value) {
  266.         case 'string':
  267.             return quote(value);
  268.  
  269.         case 'number':
  270.  
  271. // JSON numbers must be finite. Encode non-finite numbers as null.
  272.  
  273.             return isFinite(value)
  274.                 ? String(value)
  275.                 : 'null';
  276.  
  277.         case 'boolean':
  278.         case 'null':
  279.  
  280. // If the value is a boolean or null, convert it to a string. Note:
  281. // typeof null does not produce 'null'. The case is included here in
  282. // the remote chance that this gets fixed someday.
  283.  
  284.             return String(value);
  285.  
  286. // If the type is 'object', we might be dealing with an object or an array or
  287. // null.
  288.  
  289.         case 'object':
  290.  
  291. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  292. // so watch out for that case.
  293.  
  294.             if (!value) {
  295.                 return 'null';
  296.             }
  297.  
  298. // Make an array to hold the partial results of stringifying this object value.
  299.  
  300.             gap += indent;
  301.             partial = [];
  302.  
  303. // Is the value an array?
  304.  
  305.             if (Object.prototype.toString.apply(value) === '[object Array]') {
  306.  
  307. // The value is an array. Stringify every element. Use null as a placeholder
  308. // for non-JSON values.
  309.  
  310.                 length = value.length;
  311.                 for (i = 0; i < length; i += 1) {
  312.                     partial[i] = str(i, value) || 'null';
  313.                 }
  314.  
  315. // Join all of the elements together, separated with commas, and wrap them in
  316. // brackets.
  317.  
  318.                 v = partial.length === 0
  319.                     ? '[]'
  320.                     : gap
  321.                         ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
  322.                         : '[' + partial.join(',') + ']';
  323.                 gap = mind;
  324.                 return v;
  325.             }
  326.  
  327. // If the replacer is an array, use it to select the members to be stringified.
  328.  
  329.             if (rep && typeof rep === 'object') {
  330.                 length = rep.length;
  331.                 for (i = 0; i < length; i += 1) {
  332.                     if (typeof rep[i] === 'string') {
  333.                         k = rep[i];
  334.                         v = str(k, value);
  335.                         if (v) {
  336.                             partial.push(quote(k) + (
  337.                                 gap
  338.                                     ? ': '
  339.                                     : ':'
  340.                             ) + v);
  341.                         }
  342.                     }
  343.                 }
  344.             } else {
  345.  
  346. // Otherwise, iterate through all of the keys in the object.
  347.  
  348.                 for (k in value) {
  349.                     if (Object.prototype.hasOwnProperty.call(value, k)) {
  350.                         v = str(k, value);
  351.                         if (v) {
  352.                             partial.push(quote(k) + (
  353.                                 gap
  354.                                     ? ': '
  355.                                     : ':'
  356.                             ) + v);
  357.                         }
  358.                     }
  359.                 }
  360.             }
  361.  
  362. // Join all of the member texts together, separated with commas,
  363. // and wrap them in braces.
  364.  
  365.             v = partial.length === 0
  366.                 ? '{}'
  367.                 : gap
  368.                     ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
  369.                     : '{' + partial.join(',') + '}';
  370.             gap = mind;
  371.             return v;
  372.         }
  373.     }
  374.  
  375. // If the JSON object does not yet have a stringify method, give it one.
  376.  
  377.     if (typeof JSON.stringify !== 'function') {
  378.         meta = {    // table of character substitutions
  379.             '\b': '\\b',
  380.             '\t': '\\t',
  381.             '\n': '\\n',
  382.             '\f': '\\f',
  383.             '\r': '\\r',
  384.             '"': '\\"',
  385.             '\\': '\\\\'
  386.         };
  387.         JSON.stringify = function (value, replacer, space) {
  388.  
  389. // The stringify method takes a value and an optional replacer, and an optional
  390. // space parameter, and returns a JSON text. The replacer can be a function
  391. // that can replace values, or an array of strings that will select the keys.
  392. // A default replacer method can be provided. Use of the space parameter can
  393. // produce text that is more easily readable.
  394.  
  395.             var i;
  396.             gap = '';
  397.             indent = '';
  398.  
  399. // If the space parameter is a number, make an indent string containing that
  400. // many spaces.
  401.  
  402.             if (typeof space === 'number') {
  403.                 for (i = 0; i < space; i += 1) {
  404.                     indent += ' ';
  405.                 }
  406.  
  407. // If the space parameter is a string, it will be used as the indent string.
  408.  
  409.             } else if (typeof space === 'string') {
  410.                 indent = space;
  411.             }
  412.  
  413. // If there is a replacer, it must be a function or an array.
  414. // Otherwise, throw an error.
  415.  
  416.             rep = replacer;
  417.             if (replacer && typeof replacer !== 'function' &&
  418.                     (typeof replacer !== 'object' ||
  419.                     typeof replacer.length !== 'number')) {
  420.                 throw new Error('JSON.stringify');
  421.             }
  422.  
  423. // Make a fake root object containing our value under the key of ''.
  424. // Return the result of stringifying the value.
  425.  
  426.             return str('', {'': value});
  427.         };
  428.     }
  429.  
  430.  
  431. // If the JSON object does not yet have a parse method, give it one.
  432.  
  433.     if (typeof JSON.parse !== 'function') {
  434.         JSON.parse = function (text, reviver) {
  435.  
  436. // The parse method takes a text and an optional reviver function, and returns
  437. // a JavaScript value if the text is a valid JSON text.
  438.  
  439.             var j;
  440.  
  441.             function walk(holder, key) {
  442.  
  443. // The walk method is used to recursively walk the resulting structure so
  444. // that modifications can be made.
  445.  
  446.                 var k, v, value = holder[key];
  447.                 if (value && typeof value === 'object') {
  448.                     for (k in value) {
  449.                         if (Object.prototype.hasOwnProperty.call(value, k)) {
  450.                             v = walk(value, k);
  451.                             if (v !== undefined) {
  452.                                 value[k] = v;
  453.                             } else {
  454.                                 delete value[k];
  455.                             }
  456.                         }
  457.                     }
  458.                 }
  459.                 return reviver.call(holder, key, value);
  460.             }
  461.  
  462.  
  463. // Parsing happens in four stages. In the first stage, we replace certain
  464. // Unicode characters with escape sequences. JavaScript handles many characters
  465. // incorrectly, either silently deleting them, or treating them as line endings.
  466.  
  467.             text = String(text);
  468.             rx_dangerous.lastIndex = 0;
  469.             if (rx_dangerous.test(text)) {
  470.                 text = text.replace(rx_dangerous, function (a) {
  471.                     return '\\u' +
  472.                             ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  473.                 });
  474.             }
  475.  
  476. // In the second stage, we run the text against regular expressions that look
  477. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  478. // because they can cause invocation, and '=' because it can cause mutation.
  479. // But just to be safe, we want to reject all unexpected forms.
  480.  
  481. // We split the second stage into 4 regexp operations in order to work around
  482. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  483. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  484. // replace all simple value tokens with ']' characters. Third, we delete all
  485. // open brackets that follow a colon or comma or that begin the text. Finally,
  486. // we look to see that the remaining characters are only whitespace or ']' or
  487. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  488.  
  489.             if (
  490.                 rx_one.test(
  491.                     text
  492.                         .replace(rx_two, '@')
  493.                         .replace(rx_three, ']')
  494.                         .replace(rx_four, '')
  495.                 )
  496.             ) {
  497.  
  498. // In the third stage we use the eval function to compile the text into a
  499. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  500. // in JavaScript: it can begin a block or an object literal. We wrap the text
  501. // in parens to eliminate the ambiguity.
  502.  
  503.                 j = eval('(' + text + ')');
  504.  
  505. // In the optional fourth stage, we recursively walk the new structure, passing
  506. // each name/value pair to a reviver function for possible transformation.
  507.  
  508.                 return typeof reviver === 'function'
  509.                     ? walk({'': j}, '')
  510.                     : j;
  511.             }
  512.  
  513. // If the text is not JSON parseable, then a SyntaxError is thrown.
  514.  
  515.             throw new SyntaxError('JSON.parse');
  516.         };
  517.     }
  518. }());

Raw Paste


Login or Register to edit or fork this paste. It's free.