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.

json2.js 18KB

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