json.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. json.js
  3. 2013-05-26
  4. Public Domain
  5. No warranty expressed or implied. Use at your own risk.
  6. This file has been superceded by http://www.JSON.org/json2.js
  7. See http://www.JSON.org/js.html
  8. This code should be minified before deployment.
  9. See http://javascript.crockford.com/jsmin.html
  10. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  11. NOT CONTROL.
  12. This file adds these methods to JavaScript:
  13. object.toJSONString(whitelist)
  14. This method produce a JSON text from a JavaScript value.
  15. It must not contain any cyclical references. Illegal values
  16. will be excluded.
  17. The default conversion for dates is to an ISO string. You can
  18. add a toJSONString method to any date object to get a different
  19. representation.
  20. The object and array methods can take an optional whitelist
  21. argument. A whitelist is an array of strings. If it is provided,
  22. keys in objects not found in the whitelist are excluded.
  23. string.parseJSON(filter)
  24. This method parses a JSON text to produce an object or
  25. array. It can throw a SyntaxError exception.
  26. The optional filter parameter is a function which can filter and
  27. transform the results. It receives each of the keys and values, and
  28. its return value is used instead of the original value. If it
  29. returns what it received, then structure is not modified. If it
  30. returns undefined then the member is deleted.
  31. Example:
  32. // Parse the text. If a key contains the string 'date' then
  33. // convert the value to a date.
  34. myData = text.parseJSON(function (key, value) {
  35. return key.indexOf('date') >= 0 ? new Date(value) : value;
  36. });
  37. This file will break programs with improper for..in loops. See
  38. http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
  39. This file creates a global JSON object containing two methods: stringify
  40. and parse.
  41. JSON.stringify(value, replacer, space)
  42. value any JavaScript value, usually an object or array.
  43. replacer an optional parameter that determines how object
  44. values are stringified for objects. It can be a
  45. function or an array of strings.
  46. space an optional parameter that specifies the indentation
  47. of nested structures. If it is omitted, the text will
  48. be packed without extra whitespace. If it is a number,
  49. it will specify the number of spaces to indent at each
  50. level. If it is a string (such as '\t' or ' '),
  51. it contains the characters used to indent at each level.
  52. This method produces a JSON text from a JavaScript value.
  53. When an object value is found, if the object contains a toJSON
  54. method, its toJSON method will be called and the result will be
  55. stringified. A toJSON method does not serialize: it returns the
  56. value represented by the name/value pair that should be serialized,
  57. or undefined if nothing should be serialized. The toJSON method
  58. will be passed the key associated with the value, and this will be
  59. bound to the object holding the key.
  60. For example, this would serialize Dates as ISO strings.
  61. Date.prototype.toJSON = function (key) {
  62. function f(n) {
  63. // Format integers to have at least two digits.
  64. return n < 10 ? '0' + n : n;
  65. }
  66. return this.getUTCFullYear() + '-' +
  67. f(this.getUTCMonth() + 1) + '-' +
  68. f(this.getUTCDate()) + 'T' +
  69. f(this.getUTCHours()) + ':' +
  70. f(this.getUTCMinutes()) + ':' +
  71. f(this.getUTCSeconds()) + 'Z';
  72. };
  73. You can provide an optional replacer method. It will be passed the
  74. key and value of each member, with this bound to the containing
  75. object. The value that is returned from your method will be
  76. serialized. If your method returns undefined, then the member will
  77. be excluded from the serialization.
  78. If the replacer parameter is an array of strings, then it will be
  79. used to select the members to be serialized. It filters the results
  80. such that only members with keys listed in the replacer array are
  81. stringified.
  82. Values that do not have JSON representations, such as undefined or
  83. functions, will not be serialized. Such values in objects will be
  84. dropped; in arrays they will be replaced with null. You can use
  85. a replacer function to replace those with JSON values.
  86. JSON.stringify(undefined) returns undefined.
  87. The optional space parameter produces a stringification of the
  88. value that is filled with line breaks and indentation to make it
  89. easier to read.
  90. If the space parameter is a non-empty string, then that string will
  91. be used for indentation. If the space parameter is a number, then
  92. the indentation will be that many spaces.
  93. Example:
  94. text = JSON.stringify(['e', {pluribus: 'unum'}]);
  95. // text is '["e",{"pluribus":"unum"}]'
  96. text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  97. // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  98. text = JSON.stringify([new Date()], function (key, value) {
  99. return this[key] instanceof Date ?
  100. 'Date(' + this[key] + ')' : value;
  101. });
  102. // text is '["Date(---current time---)"]'
  103. JSON.parse(text, reviver)
  104. This method parses a JSON text to produce an object or array.
  105. It can throw a SyntaxError exception.
  106. The optional reviver parameter is a function that can filter and
  107. transform the results. It receives each of the keys and values,
  108. and its return value is used instead of the original value.
  109. If it returns what it received, then the structure is not modified.
  110. If it returns undefined then the member is deleted.
  111. Example:
  112. // Parse the text. Values that look like ISO date strings will
  113. // be converted to Date objects.
  114. myData = JSON.parse(text, function (key, value) {
  115. var a;
  116. if (typeof value === 'string') {
  117. a =
  118. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  119. if (a) {
  120. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  121. +a[5], +a[6]));
  122. }
  123. }
  124. return value;
  125. });
  126. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  127. var d;
  128. if (typeof value === 'string' &&
  129. value.slice(0, 5) === 'Date(' &&
  130. value.slice(-1) === ')') {
  131. d = new Date(value.slice(5, -1));
  132. if (d) {
  133. return d;
  134. }
  135. }
  136. return value;
  137. });
  138. This is a reference implementation. You are free to copy, modify, or
  139. redistribute.
  140. */
  141. /*jslint evil: true, regexp: true, unparam: true */
  142. /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
  143. call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  144. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  145. lastIndex, length, parse, parseJSON, prototype, push, replace, slice,
  146. stringify, test, toJSON, toJSONString, toString, valueOf
  147. */
  148. // Create a JSON object only if one does not already exist. We create the
  149. // methods in a closure to avoid creating global variables.
  150. if (typeof JSON !== 'object') {
  151. JSON = {};
  152. }
  153. (function () {
  154. 'use strict';
  155. function f(n) {
  156. // Format integers to have at least two digits.
  157. return n < 10 ? '0' + n : n;
  158. }
  159. if (typeof Date.prototype.toJSON !== 'function') {
  160. Date.prototype.toJSON = function (key) {
  161. return isFinite(this.valueOf())
  162. ? this.getUTCFullYear() + '-' +
  163. f(this.getUTCMonth() + 1) + '-' +
  164. f(this.getUTCDate()) + 'T' +
  165. f(this.getUTCHours()) + ':' +
  166. f(this.getUTCMinutes()) + ':' +
  167. f(this.getUTCSeconds()) + 'Z'
  168. : null;
  169. };
  170. String.prototype.toJSON =
  171. Number.prototype.toJSON =
  172. Boolean.prototype.toJSON = function (key) {
  173. return this.valueOf();
  174. };
  175. }
  176. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  177. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  178. gap,
  179. indent,
  180. meta = { // table of character substitutions
  181. '\b': '\\b',
  182. '\t': '\\t',
  183. '\n': '\\n',
  184. '\f': '\\f',
  185. '\r': '\\r',
  186. '"' : '\\"',
  187. '\\': '\\\\'
  188. },
  189. rep;
  190. function quote(string) {
  191. // If the string contains no control characters, no quote characters, and no
  192. // backslash characters, then we can safely slap some quotes around it.
  193. // Otherwise we must also replace the offending characters with safe escape
  194. // sequences.
  195. escapable.lastIndex = 0;
  196. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  197. var c = meta[a];
  198. return typeof c === 'string'
  199. ? c
  200. : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  201. }) + '"' : '"' + string + '"';
  202. }
  203. function str(key, holder) {
  204. // Produce a string from holder[key].
  205. var i, // The loop counter.
  206. k, // The member key.
  207. v, // The member value.
  208. length,
  209. mind = gap,
  210. partial,
  211. value = holder[key];
  212. // If the value has a toJSON method, call it to obtain a replacement value.
  213. if (value && typeof value === 'object' &&
  214. typeof value.toJSON === 'function') {
  215. value = value.toJSON(key);
  216. }
  217. // If we were called with a replacer function, then call the replacer to
  218. // obtain a replacement value.
  219. if (typeof rep === 'function') {
  220. value = rep.call(holder, key, value);
  221. }
  222. // What happens next depends on the value's type.
  223. switch (typeof value) {
  224. case 'string':
  225. return quote(value);
  226. case 'number':
  227. // JSON numbers must be finite. Encode non-finite numbers as null.
  228. return isFinite(value) ? String(value) : 'null';
  229. case 'boolean':
  230. case 'null':
  231. // If the value is a boolean or null, convert it to a string. Note:
  232. // typeof null does not produce 'null'. The case is included here in
  233. // the remote chance that this gets fixed someday.
  234. return String(value);
  235. // If the type is 'object', we might be dealing with an object or an array or
  236. // null.
  237. case 'object':
  238. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  239. // so watch out for that case.
  240. if (!value) {
  241. return 'null';
  242. }
  243. // Make an array to hold the partial results of stringifying this object value.
  244. gap += indent;
  245. partial = [];
  246. // Is the value an array?
  247. if (Object.prototype.toString.apply(value) === '[object Array]') {
  248. // The value is an array. Stringify every element. Use null as a placeholder
  249. // for non-JSON values.
  250. length = value.length;
  251. for (i = 0; i < length; i += 1) {
  252. partial[i] = str(i, value) || 'null';
  253. }
  254. // Join all of the elements together, separated with commas, and wrap them in
  255. // brackets.
  256. v = partial.length === 0
  257. ? '[]'
  258. : gap
  259. ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
  260. : '[' + partial.join(',') + ']';
  261. gap = mind;
  262. return v;
  263. }
  264. // If the replacer is an array, use it to select the members to be stringified.
  265. if (rep && typeof rep === 'object') {
  266. length = rep.length;
  267. for (i = 0; i < length; i += 1) {
  268. k = rep[i];
  269. if (typeof k === 'string') {
  270. v = str(k, value);
  271. if (v) {
  272. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  273. }
  274. }
  275. }
  276. } else {
  277. // Otherwise, iterate through all of the keys in the object.
  278. for (k in value) {
  279. if (Object.prototype.hasOwnProperty.call(value, k)) {
  280. v = str(k, value);
  281. if (v) {
  282. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  283. }
  284. }
  285. }
  286. }
  287. // Join all of the member texts together, separated with commas,
  288. // and wrap them in braces.
  289. v = partial.length === 0 ? '{}'
  290. : gap
  291. ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
  292. : '{' + partial.join(',') + '}';
  293. gap = mind;
  294. return v;
  295. }
  296. }
  297. // If the JSON object does not yet have a stringify method, give it one.
  298. if (typeof JSON.stringify !== 'function') {
  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. cx.lastIndex = 0;
  360. if (cx.test(text)) {
  361. text = text.replace(cx, 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 (/^[\],:{}\s]*$/
  378. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  379. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  380. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  381. // In the third stage we use the eval function to compile the text into a
  382. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  383. // in JavaScript: it can begin a block or an object literal. We wrap the text
  384. // in parens to eliminate the ambiguity.
  385. j = eval('(' + text + ')');
  386. // In the optional fourth stage, we recursively walk the new structure, passing
  387. // each name/value pair to a reviver function for possible transformation.
  388. return typeof reviver === 'function'
  389. ? walk({'': j}, '')
  390. : j;
  391. }
  392. // If the text is not JSON parseable, then a SyntaxError is thrown.
  393. throw new SyntaxError('JSON.parse');
  394. };
  395. }
  396. // Augment the basic prototypes if they have not already been augmented.
  397. // These forms are obsolete. It is recommended that JSON.stringify and
  398. // JSON.parse be used instead.
  399. }());