You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
18 KiB

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