json2.js 17 KB

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