json2.js 17 KB

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