jquery.json.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /**
  2. * jQuery JSON plugin v2.5.1
  3. * https://github.com/Krinkle/jquery-json
  4. *
  5. * @author Brantley Harris, 2009-2011
  6. * @author Timo Tijhof, 2011-2014
  7. * @source This plugin is heavily influenced by MochiKit's serializeJSON, which is
  8. * copyrighted 2005 by Bob Ippolito.
  9. * @source Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
  10. * website's http://www.json.org/json2.js, which proclaims:
  11. * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
  12. * I uphold.
  13. * @license MIT License <http://opensource.org/licenses/MIT>
  14. */
  15. (function ($) {
  16. 'use strict';
  17. var escape = /["\\\x00-\x1f\x7f-\x9f]/g,
  18. meta = {
  19. '\b': '\\b',
  20. '\t': '\\t',
  21. '\n': '\\n',
  22. '\f': '\\f',
  23. '\r': '\\r',
  24. '"': '\\"',
  25. '\\': '\\\\'
  26. },
  27. hasOwn = Object.prototype.hasOwnProperty;
  28. /**
  29. * jQuery.toJSON
  30. * Converts the given argument into a JSON representation.
  31. *
  32. * @param o {Mixed} The json-serializable *thing* to be converted
  33. *
  34. * If an object has a toJSON prototype, that will be used to get the representation.
  35. * Non-integer/string keys are skipped in the object, as are keys that point to a
  36. * function.
  37. *
  38. */
  39. $.toJSON = typeof JSON === 'object' && JSON.stringify ? JSON.stringify : function (o) {
  40. if (o === null) {
  41. return 'null';
  42. }
  43. var pairs, k, name, val,
  44. type = $.type(o);
  45. if (type === 'undefined') {
  46. return undefined;
  47. }
  48. // Also covers instantiated Number and Boolean objects,
  49. // which are typeof 'object' but thanks to $.type, we
  50. // catch them here. I don't know whether it is right
  51. // or wrong that instantiated primitives are not
  52. // exported to JSON as an {"object":..}.
  53. // We choose this path because that's what the browsers did.
  54. if (type === 'number' || type === 'boolean') {
  55. return String(o);
  56. }
  57. if (type === 'string') {
  58. return $.quoteString(o);
  59. }
  60. if (typeof o.toJSON === 'function') {
  61. return $.toJSON(o.toJSON());
  62. }
  63. if (type === 'date') {
  64. var month = o.getUTCMonth() + 1,
  65. day = o.getUTCDate(),
  66. year = o.getUTCFullYear(),
  67. hours = o.getUTCHours(),
  68. minutes = o.getUTCMinutes(),
  69. seconds = o.getUTCSeconds(),
  70. milli = o.getUTCMilliseconds();
  71. if (month < 10) {
  72. month = '0' + month;
  73. }
  74. if (day < 10) {
  75. day = '0' + day;
  76. }
  77. if (hours < 10) {
  78. hours = '0' + hours;
  79. }
  80. if (minutes < 10) {
  81. minutes = '0' + minutes;
  82. }
  83. if (seconds < 10) {
  84. seconds = '0' + seconds;
  85. }
  86. if (milli < 100) {
  87. milli = '0' + milli;
  88. }
  89. if (milli < 10) {
  90. milli = '0' + milli;
  91. }
  92. return '"' + year + '-' + month + '-' + day + 'T' +
  93. hours + ':' + minutes + ':' + seconds +
  94. '.' + milli + 'Z"';
  95. }
  96. pairs = [];
  97. if ($.isArray(o)) {
  98. for (k = 0; k < o.length; k++) {
  99. pairs.push($.toJSON(o[k]) || 'null');
  100. }
  101. return '[' + pairs.join(',') + ']';
  102. }
  103. // Any other object (plain object, RegExp, ..)
  104. // Need to do typeof instead of $.type, because we also
  105. // want to catch non-plain objects.
  106. if (typeof o === 'object') {
  107. for (k in o) {
  108. // Only include own properties,
  109. // Filter out inherited prototypes
  110. if (hasOwn.call(o, k)) {
  111. // Keys must be numerical or string. Skip others
  112. type = typeof k;
  113. if (type === 'number') {
  114. name = '"' + k + '"';
  115. } else if (type === 'string') {
  116. name = $.quoteString(k);
  117. } else {
  118. continue;
  119. }
  120. type = typeof o[k];
  121. // Invalid values like these return undefined
  122. // from toJSON, however those object members
  123. // shouldn't be included in the JSON string at all.
  124. if (type !== 'function' && type !== 'undefined') {
  125. val = $.toJSON(o[k]);
  126. pairs.push(name + ':' + val);
  127. }
  128. }
  129. }
  130. return '{' + pairs.join(',') + '}';
  131. }
  132. };
  133. /**
  134. * jQuery.evalJSON
  135. * Evaluates a given json string.
  136. *
  137. * @param str {String}
  138. */
  139. $.evalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
  140. /*jshint evil: true */
  141. return eval('(' + str + ')');
  142. };
  143. /**
  144. * jQuery.secureEvalJSON
  145. * Evals JSON in a way that is *more* secure.
  146. *
  147. * @param str {String}
  148. */
  149. $.secureEvalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
  150. var filtered =
  151. str
  152. .replace(/\\["\\\/bfnrtu]/g, '@')
  153. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  154. .replace(/(?:^|:|,)(?:\s*\[)+/g, '');
  155. if (/^[\],:{}\s]*$/.test(filtered)) {
  156. /*jshint evil: true */
  157. return eval('(' + str + ')');
  158. }
  159. throw new SyntaxError('Error parsing JSON, source is not valid.');
  160. };
  161. /**
  162. * jQuery.quoteString
  163. * Returns a string-repr of a string, escaping quotes intelligently.
  164. * Mostly a support function for toJSON.
  165. * Examples:
  166. * >>> jQuery.quoteString('apple')
  167. * "apple"
  168. *
  169. * >>> jQuery.quoteString('"Where are we going?", she asked.')
  170. * "\"Where are we going?\", she asked."
  171. */
  172. $.quoteString = function (str) {
  173. if (str.match(escape)) {
  174. return '"' + str.replace(escape, function (a) {
  175. var c = meta[a];
  176. if (typeof c === 'string') {
  177. return c;
  178. }
  179. c = a.charCodeAt();
  180. return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
  181. }) + '"';
  182. }
  183. return '"' + str + '"';
  184. };
  185. }(jQuery));