json2.js 17 KB

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