json2.js 18 KB

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