json2.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. http://www.JSON.org/json2.js
  3. 2010-11-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 code should be minified before deployment.
  8. See http://javascript.crockford.com/jsmin.html
  9. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  10. NOT CONTROL.
  11. This file creates a global JSON object containing two methods: stringify
  12. and parse.
  13. JSON.stringify(value, replacer, space)
  14. value any JavaScript value, usually an object or array.
  15. replacer an optional parameter that determines how object
  16. values are stringified for objects. It can be a
  17. function or an array of strings.
  18. space an optional parameter that specifies the indentation
  19. of nested structures. If it is omitted, the text will
  20. be packed without extra whitespace. If it is a number,
  21. it will specify the number of spaces to indent at each
  22. level. If it is a string (such as '\t' or ' '),
  23. it contains the characters used to indent at each level.
  24. This method produces a JSON text from a JavaScript value.
  25. When an object value is found, if the object contains a toJSON
  26. method, its toJSON method will be called and the result will be
  27. stringified. A toJSON method does not serialize: it returns the
  28. value represented by the name/value pair that should be serialized,
  29. or undefined if nothing should be serialized. The toJSON method
  30. will be passed the key associated with the value, and this will be
  31. bound to the value
  32. For example, this would serialize Dates as ISO strings.
  33. Date.prototype.toJSON = function (key) {
  34. function f(n) {
  35. // Format integers to have at least two digits.
  36. return n < 10 ? '0' + n : n;
  37. }
  38. return this.getUTCFullYear() + '-' +
  39. f(this.getUTCMonth() + 1) + '-' +
  40. f(this.getUTCDate()) + 'T' +
  41. f(this.getUTCHours()) + ':' +
  42. f(this.getUTCMinutes()) + ':' +
  43. f(this.getUTCSeconds()) + 'Z';
  44. };
  45. You can provide an optional replacer method. It will be passed the
  46. key and value of each member, with this bound to the containing
  47. object. The value that is returned from your method will be
  48. serialized. If your method returns undefined, then the member will
  49. be excluded from the serialization.
  50. If the replacer parameter is an array of strings, then it will be
  51. used to select the members to be serialized. It filters the results
  52. such that only members with keys listed in the replacer array are
  53. stringified.
  54. Values that do not have JSON representations, 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
  60. value that is filled with line breaks and indentation to make it
  61. easier to 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. the 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. text = JSON.stringify([new Date()], function (key, value) {
  71. return this[key] instanceof Date ?
  72. 'Date(' + this[key] + ')' : value;
  73. });
  74. // text is '["Date(---current time---)"]'
  75. JSON.parse(text, reviver)
  76. This method parses a JSON text to produce an object or array.
  77. It can throw a SyntaxError exception.
  78. The optional reviver parameter is a function that can filter and
  79. transform the results. It receives each of the keys and values,
  80. and its return value is used instead of the original value.
  81. If it returns what it received, then the structure is not modified.
  82. If it returns undefined then the member is deleted.
  83. Example:
  84. // Parse the text. Values that look like ISO date strings will
  85. // be converted to Date objects.
  86. myData = JSON.parse(text, function (key, value) {
  87. var a;
  88. if (typeof value === 'string') {
  89. a =
  90. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  91. if (a) {
  92. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  93. +a[5], +a[6]));
  94. }
  95. }
  96. return value;
  97. });
  98. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  99. var d;
  100. if (typeof value === 'string' &&
  101. value.slice(0, 5) === 'Date(' &&
  102. value.slice(-1) === ')') {
  103. d = new Date(value.slice(5, -1));
  104. if (d) {
  105. return d;
  106. }
  107. }
  108. return value;
  109. });
  110. This is a reference implementation. You are free to copy, modify, or
  111. redistribute.
  112. */
  113. /*jslint evil: true, strict: false, regexp: false */
  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. if (!this.JSON2)
  123. {
  124. this.JSON2 = {};
  125. }
  126. (function () {
  127. "use strict";
  128. function f(n) {
  129. // Format integers to have at least two digits.
  130. return n < 10 ? '0' + n : n;
  131. }
  132. if (typeof Date.prototype.toJSON !== 'function') {
  133. Date.prototype.toJSON = function (key) {
  134. return isFinite(this.valueOf()) ?
  135. this.getUTCFullYear() + '-' +
  136. f(this.getUTCMonth() + 1) + '-' +
  137. f(this.getUTCDate()) + 'T' +
  138. f(this.getUTCHours()) + ':' +
  139. f(this.getUTCMinutes()) + ':' +
  140. f(this.getUTCSeconds()) + 'Z' : null;
  141. };
  142. String.prototype.toJSON =
  143. Number.prototype.toJSON =
  144. Boolean.prototype.toJSON = function (key) {
  145. return this.valueOf();
  146. };
  147. }
  148. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  149. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  150. gap,
  151. indent,
  152. meta = { // table of character substitutions
  153. '\b': '\\b',
  154. '\t': '\\t',
  155. '\n': '\\n',
  156. '\f': '\\f',
  157. '\r': '\\r',
  158. '"' : '\\"',
  159. '\\': '\\\\'
  160. },
  161. rep;
  162. function quote(string) {
  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. var i, // The loop counter.
  174. k, // The member key.
  175. v, // The member value.
  176. length,
  177. mind = gap,
  178. partial,
  179. value = holder[key];
  180. if (value && typeof value === 'object' &&
  181. typeof value.toJSON === 'function') {
  182. value = value.toJSON(key);
  183. }
  184. if (typeof rep === 'function') {
  185. value = rep.call(holder, key, value);
  186. }
  187. switch (typeof value) {
  188. case 'string':
  189. return quote(value);
  190. case 'number':
  191. return isFinite(value) ? String(value) : 'null';
  192. case 'boolean':
  193. case 'null':
  194. return String(value);
  195. case 'object':
  196. if (!value) {
  197. return 'null';
  198. }
  199. gap += indent;
  200. partial = [];
  201. if (Object.prototype.toString.apply(value) === '[object Array]') {
  202. length = value.length;
  203. for (i = 0; i < length; i += 1) {
  204. partial[i] = str(i, value) || 'null';
  205. }
  206. v = partial.length === 0 ? '[]' :
  207. gap ? '[\n' + gap +
  208. partial.join(',\n' + gap) + '\n' +
  209. mind + ']' :
  210. '[' + partial.join(',') + ']';
  211. gap = mind;
  212. return v;
  213. }
  214. if (rep && typeof rep === 'object') {
  215. length = rep.length;
  216. for (i = 0; i < length; i += 1) {
  217. k = rep[i];
  218. if (typeof k === 'string') {
  219. v = str(k, value);
  220. if (v) {
  221. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  222. }
  223. }
  224. }
  225. } else {
  226. for (k in value) {
  227. if (Object.hasOwnProperty.call(value, k)) {
  228. v = str(k, value);
  229. if (v) {
  230. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  231. }
  232. }
  233. }
  234. }
  235. v = partial.length === 0 ? '{}' :
  236. gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
  237. mind + '}' : '{' + partial.join(',') + '}';
  238. gap = mind;
  239. return v;
  240. }
  241. }
  242. if (typeof JSON2.stringify !== 'function') {
  243. JSON2.stringify = function (value, replacer, space) {
  244. var i;
  245. gap = '';
  246. indent = '';
  247. if (typeof space === 'number') {
  248. for (i = 0; i < space; i += 1) {
  249. indent += ' ';
  250. }
  251. } else if (typeof space === 'string') {
  252. indent = space;
  253. }
  254. rep = replacer;
  255. if (replacer && typeof replacer !== 'function' &&
  256. (typeof replacer !== 'object' ||
  257. typeof replacer.length !== 'number')) {
  258. throw new Error('JSON2.stringify');
  259. }
  260. return str('', {'': value});
  261. };
  262. }
  263. if (typeof JSON2.parse !== 'function') {
  264. JSON2.parse = function (text, reviver) {
  265. var j;
  266. function walk(holder, key) {
  267. var k, v, value = holder[key];
  268. if (value && typeof value === 'object') {
  269. for (k in value) {
  270. if (Object.hasOwnProperty.call(value, k)) {
  271. v = walk(value, k);
  272. if (v !== undefined) {
  273. value[k] = v;
  274. } else {
  275. delete value[k];
  276. }
  277. }
  278. }
  279. }
  280. return reviver.call(holder, key, value);
  281. }
  282. text = String(text);
  283. cx.lastIndex = 0;
  284. if (cx.test(text)) {
  285. text = text.replace(cx, function (a) {
  286. return '\\u' +
  287. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  288. });
  289. }
  290. if (/^[\],:{}\s]*$/
  291. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  292. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  293. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  294. j = eval('(' + text + ')');
  295. return typeof reviver === 'function' ?
  296. walk({'': j}, '') : j;
  297. }
  298. throw new SyntaxError('JSON2.parse');
  299. };
  300. }
  301. }());