json2.js 16 KB

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