json.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. /*
  2. * jQuery JSON Plugin
  3. * version: 1.0 (2008-04-17)
  4. *
  5. * This document is licensed as free software under the terms of the
  6. * MIT License: http://www.opensource.org/licenses/mit-license.php
  7. *
  8. * Brantley Harris technically wrote this plugin, but it is based somewhat
  9. * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
  10. * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
  11. * I uphold. I really just cleaned it up.
  12. *
  13. * It is also based heavily on MochiKit's serializeJSON, which is
  14. * copywrited 2005 by Bob Ippolito.
  15. */
  16. (function($) {
  17. function toIntegersAtLease(n)
  18. // Format integers to have at least two digits.
  19. {
  20. return n < 10 ? '0' + n : n;
  21. }
  22. Date.prototype.toJSON = function(date)
  23. // Yes, it polutes the Date namespace, but we'll allow it here, as
  24. // it's damned usefull.
  25. {
  26. return this.getUTCFullYear() + '-' +
  27. toIntegersAtLease(this.getUTCMonth()) + '-' +
  28. toIntegersAtLease(this.getUTCDate());
  29. };
  30. var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
  31. var meta = { // table of character substitutions
  32. '\b': '\\b',
  33. '\t': '\\t',
  34. '\n': '\\n',
  35. '\f': '\\f',
  36. '\r': '\\r',
  37. '"' : '\\"',
  38. '\\': '\\\\'
  39. };
  40. $.quoteString = function(string)
  41. // Places quotes around a string, inteligently.
  42. // If the string contains no control characters, no quote characters, and no
  43. // backslash characters, then we can safely slap some quotes around it.
  44. // Otherwise we must also replace the offending characters with safe escape
  45. // sequences.
  46. {
  47. //if (escapeable.test(string))
  48. //{
  49. return '"' + string.replace(escapeable, function (a)
  50. {
  51. var c = meta[a];
  52. if (typeof c === 'string') {
  53. return c;
  54. }
  55. c = a.charCodeAt();
  56. return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
  57. }) + '"';
  58. //}
  59. //else{
  60. // string = string.replace('\n','\\n');
  61. //}
  62. return '"' + string + '"';
  63. };
  64. $.toJSON = function(o, compact)
  65. {
  66. var type = typeof(o);
  67. if (type == "undefined")
  68. return "undefined";
  69. else if (type == "number" || type == "boolean")
  70. return o + "";
  71. else if (o === null)
  72. return "null";
  73. // Is it a string?
  74. if (type == "string")
  75. {
  76. var str = $.quoteString(o);
  77. return str;
  78. }
  79. // Does it have a .toJSON function?
  80. if (type == "object" && typeof o.toJSON == "function")
  81. return o.toJSON(compact);
  82. // Is it an array?
  83. if (type != "function" && typeof(o.length) == "number")
  84. {
  85. var ret = [];
  86. for (var i = 0; i < o.length; i++) {
  87. ret.push( $.toJSON(o[i], compact) );
  88. }
  89. if (compact)
  90. return "[" + ret.join(",") + "]";
  91. else
  92. return "[" + ret.join(", ") + "]";
  93. }
  94. // If it's a function, we have to warn somebody!
  95. if (type == "function") {
  96. throw new TypeError("Unable to convert object of type 'function' to json.");
  97. }
  98. // It's probably an object, then.
  99. var ret = [];
  100. for (var k in o) {
  101. var name;
  102. type = typeof(k);
  103. if (type == "number")
  104. name = '"' + k + '"';
  105. else if (type == "string")
  106. name = $.quoteString(k);
  107. else
  108. continue; //skip non-string or number keys
  109. var val = $.toJSON(o[k], compact);
  110. if (typeof(val) != "string") {
  111. // skip non-serializable values
  112. continue;
  113. }
  114. if (compact)
  115. ret.push(name + ":" + val);
  116. else
  117. ret.push(name + ": " + val);
  118. }
  119. return "{" + ret.join(", ") + "}";
  120. };
  121. $.compactJSON = function(o)
  122. {
  123. return $.toJSON(o, true);
  124. };
  125. $.evalJSON = function(src)
  126. // Evals JSON that we know to be safe.
  127. {
  128. return eval("(" + src + ")");
  129. };
  130. $.secureEvalJSON = function(src)
  131. // Evals JSON in a way that is *more* secure.
  132. {
  133. var filtered = src;
  134. filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
  135. filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
  136. filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
  137. if (/^[\],:{}\s]*$/.test(filtered))
  138. return eval("(" + src + ")");
  139. else
  140. throw new SyntaxError("Error parsing JSON, source is not valid.");
  141. };
  142. })(jQuery);