PageRenderTime 1128ms CodeModel.GetById 26ms RepoModel.GetById 7ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/Scripts/json2.js

#
JavaScript | 487 lines | 318 code | 12 blank | 157 comment | 2 complexity | 2ee84c1e82528e5e09c645cf07c97877 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. /*
  2. http://www.JSON.org/json2.js
  3. 2011-10-19
  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, regexp: true */
  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. var JSON;
  123. if (!JSON) {
  124. JSON = {};
  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'
  141. : null;
  142. };
  143. String.prototype.toJSON =
  144. Number.prototype.toJSON =
  145. Boolean.prototype.toJSON = function (key) {
  146. return this.valueOf();
  147. };
  148. }
  149. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  150. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  151. gap,
  152. indent,
  153. meta = { // table of character substitutions
  154. '\b': '\\b',
  155. '\t': '\\t',
  156. '\n': '\\n',
  157. '\f': '\\f',
  158. '\r': '\\r',
  159. '"' : '\\"',
  160. '\\': '\\\\'
  161. },
  162. rep;
  163. function quote(string) {
  164. // If the string contains no control characters, no quote characters, and no
  165. // backslash characters, then we can safely slap some quotes around it.
  166. // Otherwise we must also replace the offending characters with safe escape
  167. // sequences.
  168. escapable.lastIndex = 0;
  169. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  170. var c = meta[a];
  171. return typeof c === 'string'
  172. ? c
  173. : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  174. }) + '"' : '"' + string + '"';
  175. }
  176. function str(key, holder) {
  177. // Produce a string from holder[key].
  178. var i, // The loop counter.
  179. k, // The member key.
  180. v, // The member value.
  181. length,
  182. mind = gap,
  183. partial,
  184. value = holder[key];
  185. // If the value has a toJSON method, call it to obtain a replacement value.
  186. if (value && typeof value === 'object' &&
  187. typeof value.toJSON === 'function') {
  188. value = value.toJSON(key);
  189. }
  190. // If we were called with a replacer function, then call the replacer to
  191. // obtain a replacement value.
  192. if (typeof rep === 'function') {
  193. value = rep.call(holder, key, value);
  194. }
  195. // What happens next depends on the value's type.
  196. switch (typeof value) {
  197. case 'string':
  198. return quote(value);
  199. case 'number':
  200. // JSON numbers must be finite. Encode non-finite numbers as null.
  201. return isFinite(value) ? String(value) : 'null';
  202. case 'boolean':
  203. case 'null':
  204. // If the value is a boolean or null, convert it to a string. Note:
  205. // typeof null does not produce 'null'. The case is included here in
  206. // the remote chance that this gets fixed someday.
  207. return String(value);
  208. // If the type is 'object', we might be dealing with an object or an array or
  209. // null.
  210. case 'object':
  211. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  212. // so watch out for that case.
  213. if (!value) {
  214. return 'null';
  215. }
  216. // Make an array to hold the partial results of stringifying this object value.
  217. gap += indent;
  218. partial = [];
  219. // Is the value an array?
  220. if (Object.prototype.toString.apply(value) === '[object Array]') {
  221. // The value is an array. Stringify every element. Use null as a placeholder
  222. // for non-JSON values.
  223. length = value.length;
  224. for (i = 0; i < length; i += 1) {
  225. partial[i] = str(i, value) || 'null';
  226. }
  227. // Join all of the elements together, separated with commas, and wrap them in
  228. // brackets.
  229. v = partial.length === 0
  230. ? '[]'
  231. : gap
  232. ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
  233. : '[' + partial.join(',') + ']';
  234. gap = mind;
  235. return v;
  236. }
  237. // If the replacer is an array, use it to select the members to be stringified.
  238. if (rep && typeof rep === 'object') {
  239. length = rep.length;
  240. for (i = 0; i < length; i += 1) {
  241. if (typeof rep[i] === 'string') {
  242. k = rep[i];
  243. v = str(k, value);
  244. if (v) {
  245. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  246. }
  247. }
  248. }
  249. } else {
  250. // Otherwise, iterate through all of the keys in the object.
  251. for (k in value) {
  252. if (Object.prototype.hasOwnProperty.call(value, k)) {
  253. v = str(k, value);
  254. if (v) {
  255. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  256. }
  257. }
  258. }
  259. }
  260. // Join all of the member texts together, separated with commas,
  261. // and wrap them in braces.
  262. v = partial.length === 0
  263. ? '{}'
  264. : gap
  265. ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
  266. : '{' + partial.join(',') + '}';
  267. gap = mind;
  268. return v;
  269. }
  270. }
  271. // If the JSON object does not yet have a stringify method, give it one.
  272. if (typeof JSON.stringify !== 'function') {
  273. JSON.stringify = function (value, replacer, space) {
  274. // The stringify method takes a value and an optional replacer, and an optional
  275. // space parameter, and returns a JSON text. The replacer can be a function
  276. // that can replace values, or an array of strings that will select the keys.
  277. // A default replacer method can be provided. Use of the space parameter can
  278. // produce text that is more easily readable.
  279. var i;
  280. gap = '';
  281. indent = '';
  282. // If the space parameter is a number, make an indent string containing that
  283. // many spaces.
  284. if (typeof space === 'number') {
  285. for (i = 0; i < space; i += 1) {
  286. indent += ' ';
  287. }
  288. // If the space parameter is a string, it will be used as the indent string.
  289. } else if (typeof space === 'string') {
  290. indent = space;
  291. }
  292. // If there is a replacer, it must be a function or an array.
  293. // Otherwise, throw an error.
  294. rep = replacer;
  295. if (replacer && typeof replacer !== 'function' &&
  296. (typeof replacer !== 'object' ||
  297. typeof replacer.length !== 'number')) {
  298. throw new Error('JSON.stringify');
  299. }
  300. // Make a fake root object containing our value under the key of ''.
  301. // Return the result of stringifying the value.
  302. return str('', {'': value});
  303. };
  304. }
  305. // If the JSON object does not yet have a parse method, give it one.
  306. if (typeof JSON.parse !== 'function') {
  307. JSON.parse = function (text, reviver) {
  308. // The parse method takes a text and an optional reviver function, and returns
  309. // a JavaScript value if the text is a valid JSON text.
  310. var j;
  311. function walk(holder, key) {
  312. // The walk method is used to recursively walk the resulting structure so
  313. // that modifications can be made.
  314. var k, v, value = holder[key];
  315. if (value && typeof value === 'object') {
  316. for (k in value) {
  317. if (Object.prototype.hasOwnProperty.call(value, k)) {
  318. v = walk(value, k);
  319. if (v !== undefined) {
  320. value[k] = v;
  321. } else {
  322. delete value[k];
  323. }
  324. }
  325. }
  326. }
  327. return reviver.call(holder, key, value);
  328. }
  329. // Parsing happens in four stages. In the first stage, we replace certain
  330. // Unicode characters with escape sequences. JavaScript handles many characters
  331. // incorrectly, either silently deleting them, or treating them as line endings.
  332. text = String(text);
  333. cx.lastIndex = 0;
  334. if (cx.test(text)) {
  335. text = text.replace(cx, function (a) {
  336. return '\\u' +
  337. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  338. });
  339. }
  340. // In the second stage, we run the text against regular expressions that look
  341. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  342. // because they can cause invocation, and '=' because it can cause mutation.
  343. // But just to be safe, we want to reject all unexpected forms.
  344. // We split the second stage into 4 regexp operations in order to work around
  345. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  346. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  347. // replace all simple value tokens with ']' characters. Third, we delete all
  348. // open brackets that follow a colon or comma or that begin the text. Finally,
  349. // we look to see that the remaining characters are only whitespace or ']' or
  350. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  351. if (/^[\],:{}\s]*$/
  352. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  353. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  354. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  355. // In the third stage we use the eval function to compile the text into a
  356. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  357. // in JavaScript: it can begin a block or an object literal. We wrap the text
  358. // in parens to eliminate the ambiguity.
  359. j = eval('(' + text + ')');
  360. // In the optional fourth stage, we recursively walk the new structure, passing
  361. // each name/value pair to a reviver function for possible transformation.
  362. return typeof reviver === 'function'
  363. ? walk({'': j}, '')
  364. : j;
  365. }
  366. // If the text is not JSON parseable, then a SyntaxError is thrown.
  367. throw new SyntaxError('JSON.parse');
  368. };
  369. }
  370. }());