jqplot.json2.js 17 KB

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