2
0

json2.js 17 KB

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