json.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. json.js
  3. 2007-03-06
  4. modified by yatrack.cn 2007-03-18
  5. Public Domain
  6. This file adds these methods to JavaScript:
  7. array.toJSONString()
  8. boolean.toJSONString()
  9. date.toJSONString()
  10. number.toJSONString()
  11. object.toJSONString()
  12. string.toJSONString()
  13. These methods produce a JSON text from a JavaScript value.
  14. It must not contain any cyclical references. Illegal values
  15. will be excluded.
  16. The default conversion for dates is to an ISO string. You can
  17. add a toJSONString method to any date object to get a different
  18. representation.
  19. string.parseJSON(filter)
  20. This method parses a JSON text to produce an object or
  21. array. It can throw a SyntaxError exception.
  22. The optional filter parameter is a function which can filter and
  23. transform the results. It receives each of the keys and values, and
  24. its return value is used instead of the original value. If it
  25. returns what it received, then structure is not modified. If it
  26. returns undefined then the member is deleted.
  27. Example:
  28. // Parse the text. If a key contains the string 'date' then
  29. // convert the value to a date.
  30. myData = text.parseJSON(function (key, value) {
  31. return key.indexOf('date') >= 0 ? new Date(value) : value;
  32. });
  33. It is expected that these methods will formally become part of the
  34. JavaScript Programming Language in the Fourth Edition of the
  35. ECMAScript standard in 2008.
  36. */
  37. /*
  38. The global object JSON contains two methods.
  39. JSON.stringify(value) takes a JavaScript value and produces a JSON text.
  40. The value must not be cyclical.
  41. JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
  42. return false if there is an error.
  43. */
  44. var JSON = function ()
  45. {
  46. var m = {
  47. '\b': '\\b',
  48. '\t': '\\t',
  49. '\n': '\\n',
  50. '\f': '\\f',
  51. '\r': '\\r',
  52. '"' : '\\"',
  53. '\\': '\\\\'
  54. };
  55. var s = {
  56. 'boolean': function (x) {
  57. return String(x);
  58. },
  59. 'date': function (x) {
  60. // Ultimately, this method will be equivalent to the date.toISOString method.
  61. function f(n) {
  62. // Format integers to have at least two digits.
  63. return n < 10 ? '0' + n : n;
  64. };
  65. return '"' + x.getFullYear() + '-' +
  66. f(x.getMonth() + 1) + '-' +
  67. f(x.getDate()) + 'T' +
  68. f(x.getHours()) + ':' +
  69. f(x.getMinutes()) + ':' +
  70. f(x.getSeconds()) + '"';
  71. },
  72. 'number': function (x) {
  73. // JSON numbers must be finite. Encode non-finite numbers as null.
  74. return isFinite(x) ? String(x) : "null";
  75. },
  76. 'object':function (x) {
  77. var a = ['{'], // The array holding the text fragments.
  78. b, // A boolean indicating that a comma is required.
  79. k, // The current key.
  80. v; // The current value.
  81. function p(s) {
  82. // p accumulates text fragment pairs in an array. It inserts a comma before all
  83. // except the first fragment pair.
  84. if (b) {
  85. a.push(',');
  86. }
  87. a.push(JSON.stringify(k), ':', s);
  88. b = true;
  89. };
  90. // Iterate through all of the keys in the object, ignoring the proto chain.
  91. for (k in x) {
  92. if (x.hasOwnProperty(k)) {
  93. v = x[k];
  94. switch (typeof v) {
  95. // Values without a JSON representation are ignored.
  96. case 'undefined':
  97. case 'function':
  98. case 'unknown':
  99. break;
  100. // Serialize a JavaScript object value. Ignore objects that lack the
  101. // toJSONString method. Due to a specification error in ECMAScript,
  102. // typeof null is 'object', so watch out for that case.
  103. case 'object':
  104. if (v) {
  105. /*
  106. if (typeof v.toJSONString === 'function') {
  107. p(v.toJSONString());
  108. }
  109. */
  110. p(JSON.stringify(v));
  111. } else {
  112. p("null");
  113. }
  114. break;
  115. default:
  116. p(JSON.stringify(v));
  117. }
  118. }
  119. }
  120. // Join all of the fragments together and return.
  121. a.push('}');
  122. return a.join('');
  123. },
  124. 'array':function (x) {
  125. var a = ['['], // The array holding the text fragments.
  126. b, // A boolean indicating that a comma is required.
  127. i, // Loop counter.
  128. l = x.length,
  129. v; // The value to be stringified.
  130. function p(s) {
  131. // p accumulates text fragments in an array. It inserts a comma before all
  132. // except the first fragment.
  133. if (b) {
  134. a.push(',');
  135. }
  136. a.push(s);
  137. b = true;
  138. };
  139. // For each value in this array...
  140. for (i = 0; i < l; i += 1) {
  141. v = x[i];
  142. switch (typeof v) {
  143. // Values without a JSON representation are ignored.
  144. case 'undefined':
  145. case 'function':
  146. case 'unknown':
  147. break;
  148. // Serialize a JavaScript object value. Ignore objects thats lack the
  149. // toJSONString method. Due to a specification error in ECMAScript,
  150. // typeof null is 'object', so watch out for that case.
  151. case 'object':
  152. if (v) {
  153. /*
  154. if (typeof v.toJSONString === 'function') {
  155. p(v.toJSONString());
  156. }
  157. */
  158. p(JSON.stringify(v));
  159. } else {
  160. p("null");
  161. }
  162. break;
  163. // Otherwise, serialize the value.
  164. default:
  165. p(JSON.stringify(v));
  166. }
  167. }
  168. // Join all of the fragments together and return.
  169. a.push(']');
  170. return a.join('');
  171. },
  172. 'string': function (x) {
  173. // If the string contains no control characters, no quote characters, and no
  174. // backslash characters, then we can simply slap some quotes around it.
  175. // Otherwise we must also replace the offending characters with safe
  176. // sequences.
  177. if (/["\\\x00-\x1f]/.test(x)) {
  178. return '"' + x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
  179. var c = m[b];
  180. if (c) {
  181. return c;
  182. }
  183. c = b.charCodeAt();
  184. return '\\u00' +
  185. Math.floor(c / 16).toString(16) +
  186. (c % 16).toString(16);
  187. }) + '"';
  188. }
  189. return '"' + x + '"';
  190. }
  191. };
  192. return {
  193. copyright: '(c)2005 JSON.org',
  194. license: 'http://www.JSON.org/license.html',
  195. /*
  196. Stringify a JavaScript value, producing a JSON text.
  197. */
  198. stringify: function (v) {
  199. //alert("typeof v:"+typeof v);
  200. var vType = typeof(v);
  201. if(vType === 'object')
  202. {
  203. if(v instanceof Date)
  204. {
  205. vType = 'date';
  206. }
  207. else if(v instanceof Array)
  208. {
  209. vType = 'array';
  210. }
  211. }
  212. //alert(vType);
  213. var f = s[vType];
  214. //alert(f);
  215. if (f) {
  216. v = f(v);
  217. if (typeof v == 'string') {
  218. return v;
  219. }
  220. }
  221. return null;
  222. },
  223. /*
  224. Parse a JSON text, producing a JavaScript value.
  225. It returns false if there is a syntax error.
  226. */
  227. parse: function (text) {
  228. //alert("text == " + text);
  229. try {
  230. return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
  231. text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
  232. eval('(' + text + ')');
  233. } catch (e) {
  234. return false;
  235. }
  236. }
  237. };
  238. }();