json3.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  2. ;(function (window) {
  3. // Convenience aliases.
  4. var getClass = {}.toString, isProperty, forEach, undef;
  5. // Detect the `define` function exposed by asynchronous module loaders. The
  6. // strict `define` check is necessary for compatibility with `r.js`.
  7. var isLoader = typeof define === "function" && define.amd;
  8. // Detect native implementations.
  9. var nativeJSON = typeof JSON == "object" && JSON;
  10. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  11. // available.
  12. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  13. if (JSON3 && nativeJSON) {
  14. // Explicitly delegate to the native `stringify` and `parse`
  15. // implementations in CommonJS environments.
  16. JSON3.stringify = nativeJSON.stringify;
  17. JSON3.parse = nativeJSON.parse;
  18. } else {
  19. // Export for web browsers, JavaScript engines, and asynchronous module
  20. // loaders, using the global `JSON` object if available.
  21. JSON3 = window.JSON = nativeJSON || {};
  22. }
  23. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  24. var isExtended = new Date(-3509827334573292);
  25. try {
  26. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  27. // results for certain dates in Opera >= 10.53.
  28. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  29. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  30. // but clips the values returned by the date methods to the range of
  31. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  33. } catch (exception) {}
  34. // Internal: Determines whether the native `JSON.stringify` and `parse`
  35. // implementations are spec-compliant. Based on work by Ken Snyder.
  36. function has(name) {
  37. if (has[name] !== undef) {
  38. // Return cached feature test result.
  39. return has[name];
  40. }
  41. var isSupported;
  42. if (name == "bug-string-char-index") {
  43. // IE <= 7 doesn't support accessing string characters using square
  44. // bracket notation. IE 8 only supports this for primitives.
  45. isSupported = "a"[0] != "a";
  46. } else if (name == "json") {
  47. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  48. // supported.
  49. isSupported = has("json-stringify") && has("json-parse");
  50. } else {
  51. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  52. // Test `JSON.stringify`.
  53. if (name == "json-stringify") {
  54. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  55. if (stringifySupported) {
  56. // A test function object with a custom `toJSON` method.
  57. (value = function () {
  58. return 1;
  59. }).toJSON = value;
  60. try {
  61. stringifySupported =
  62. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  63. // primitives as object literals.
  64. stringify(0) === "0" &&
  65. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  66. // literals.
  67. stringify(new Number()) === "0" &&
  68. stringify(new String()) == '""' &&
  69. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  70. // does not define a canonical JSON representation (this applies to
  71. // objects with `toJSON` properties as well, *unless* they are nested
  72. // within an object or array).
  73. stringify(getClass) === undef &&
  74. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  75. // FF 3.1b3 pass this test.
  76. stringify(undef) === undef &&
  77. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  78. // respectively, if the value is omitted entirely.
  79. stringify() === undef &&
  80. // FF 3.1b1, 2 throw an error if the given value is not a number,
  81. // string, array, object, Boolean, or `null` literal. This applies to
  82. // objects with custom `toJSON` methods as well, unless they are nested
  83. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  84. // methods entirely.
  85. stringify(value) === "1" &&
  86. stringify([value]) == "[1]" &&
  87. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  88. // `"[null]"`.
  89. stringify([undef]) == "[null]" &&
  90. // YUI 3.0.0b1 fails to serialize `null` literals.
  91. stringify(null) == "null" &&
  92. // FF 3.1b1, 2 halts serialization if an array contains a function:
  93. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  94. // elides non-JSON values from objects and arrays, unless they
  95. // define custom `toJSON` methods.
  96. stringify([undef, getClass, null]) == "[null,null,null]" &&
  97. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  98. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  99. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  100. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  101. stringify(null, value) === "1" &&
  102. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  103. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  104. // serialize extended years.
  105. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  106. // The milliseconds are optional in ES 5, but required in 5.1.
  107. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  108. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  109. // four-digit years instead of six-digit years. Credits: @Yaffle.
  110. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  111. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  112. // values less than 1000. Credits: @Yaffle.
  113. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  114. } catch (exception) {
  115. stringifySupported = false;
  116. }
  117. }
  118. isSupported = stringifySupported;
  119. }
  120. // Test `JSON.parse`.
  121. if (name == "json-parse") {
  122. var parse = JSON3.parse;
  123. if (typeof parse == "function") {
  124. try {
  125. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  126. // Conforming implementations should also coerce the initial argument to
  127. // a string prior to parsing.
  128. if (parse("0") === 0 && !parse(false)) {
  129. // Simple parsing test.
  130. value = parse(serialized);
  131. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  132. if (parseSupported) {
  133. try {
  134. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  135. parseSupported = !parse('"\t"');
  136. } catch (exception) {}
  137. if (parseSupported) {
  138. try {
  139. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  140. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  141. // certain octal literals.
  142. parseSupported = parse("01") !== 1;
  143. } catch (exception) {}
  144. }
  145. if (parseSupported) {
  146. try {
  147. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  148. // points. These environments, along with FF 3.1b1 and 2,
  149. // also allow trailing commas in JSON objects and arrays.
  150. parseSupported = parse("1.") !== 1;
  151. } catch (exception) {}
  152. }
  153. }
  154. }
  155. } catch (exception) {
  156. parseSupported = false;
  157. }
  158. }
  159. isSupported = parseSupported;
  160. }
  161. }
  162. return has[name] = !!isSupported;
  163. }
  164. if (!has("json")) {
  165. // Common `[[Class]]` name aliases.
  166. var functionClass = "[object Function]";
  167. var dateClass = "[object Date]";
  168. var numberClass = "[object Number]";
  169. var stringClass = "[object String]";
  170. var arrayClass = "[object Array]";
  171. var booleanClass = "[object Boolean]";
  172. // Detect incomplete support for accessing string characters by index.
  173. var charIndexBuggy = has("bug-string-char-index");
  174. // Define additional utility methods if the `Date` methods are buggy.
  175. if (!isExtended) {
  176. var floor = Math.floor;
  177. // A mapping between the months of the year and the number of days between
  178. // January 1st and the first of the respective month.
  179. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  180. // Internal: Calculates the number of days between the Unix epoch and the
  181. // first day of the given month.
  182. var getDay = function (year, month) {
  183. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  184. };
  185. }
  186. // Internal: Determines if a property is a direct property of the given
  187. // object. Delegates to the native `Object#hasOwnProperty` method.
  188. if (!(isProperty = {}.hasOwnProperty)) {
  189. isProperty = function (property) {
  190. var members = {}, constructor;
  191. if ((members.__proto__ = null, members.__proto__ = {
  192. // The *proto* property cannot be set multiple times in recent
  193. // versions of Firefox and SeaMonkey.
  194. "toString": 1
  195. }, members).toString != getClass) {
  196. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  197. // supports the mutable *proto* property.
  198. isProperty = function (property) {
  199. // Capture and break the object's prototype chain (see section 8.6.2
  200. // of the ES 5.1 spec). The parenthesized expression prevents an
  201. // unsafe transformation by the Closure Compiler.
  202. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  203. // Restore the original prototype chain.
  204. this.__proto__ = original;
  205. return result;
  206. };
  207. } else {
  208. // Capture a reference to the top-level `Object` constructor.
  209. constructor = members.constructor;
  210. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  211. // other environments.
  212. isProperty = function (property) {
  213. var parent = (this.constructor || constructor).prototype;
  214. return property in this && !(property in parent && this[property] === parent[property]);
  215. };
  216. }
  217. members = null;
  218. return isProperty.call(this, property);
  219. };
  220. }
  221. // Internal: A set of primitive types used by `isHostType`.
  222. var PrimitiveTypes = {
  223. 'boolean': 1,
  224. 'number': 1,
  225. 'string': 1,
  226. 'undefined': 1
  227. };
  228. // Internal: Determines if the given object `property` value is a
  229. // non-primitive.
  230. var isHostType = function (object, property) {
  231. var type = typeof object[property];
  232. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  233. };
  234. // Internal: Normalizes the `for...in` iteration algorithm across
  235. // environments. Each enumerated key is yielded to a `callback` function.
  236. forEach = function (object, callback) {
  237. var size = 0, Properties, members, property;
  238. // Tests for bugs in the current environment's `for...in` algorithm. The
  239. // `valueOf` property inherits the non-enumerable flag from
  240. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  241. (Properties = function () {
  242. this.valueOf = 0;
  243. }).prototype.valueOf = 0;
  244. // Iterate over a new instance of the `Properties` class.
  245. members = new Properties();
  246. for (property in members) {
  247. // Ignore all properties inherited from `Object.prototype`.
  248. if (isProperty.call(members, property)) {
  249. size++;
  250. }
  251. }
  252. Properties = members = null;
  253. // Normalize the iteration algorithm.
  254. if (!size) {
  255. // A list of non-enumerable properties inherited from `Object.prototype`.
  256. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  257. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  258. // properties.
  259. forEach = function (object, callback) {
  260. var isFunction = getClass.call(object) == functionClass, property, length;
  261. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  262. for (property in object) {
  263. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  264. // certain conditions; IE does not.
  265. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  266. callback(property);
  267. }
  268. }
  269. // Manually invoke the callback for each non-enumerable property.
  270. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  271. };
  272. } else if (size == 2) {
  273. // Safari <= 2.0.4 enumerates shadowed properties twice.
  274. forEach = function (object, callback) {
  275. // Create a set of iterated properties.
  276. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  277. for (property in object) {
  278. // Store each property name to prevent double enumeration. The
  279. // `prototype` property of functions is not enumerated due to cross-
  280. // environment inconsistencies.
  281. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  282. callback(property);
  283. }
  284. }
  285. };
  286. } else {
  287. // No bugs detected; use the standard `for...in` algorithm.
  288. forEach = function (object, callback) {
  289. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  290. for (property in object) {
  291. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  292. callback(property);
  293. }
  294. }
  295. // Manually invoke the callback for the `constructor` property due to
  296. // cross-environment inconsistencies.
  297. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  298. callback(property);
  299. }
  300. };
  301. }
  302. return forEach(object, callback);
  303. };
  304. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  305. // `filter` argument may specify either a function that alters how object and
  306. // array members are serialized, or an array of strings and numbers that
  307. // indicates which properties should be serialized. The optional `width`
  308. // argument may be either a string or number that specifies the indentation
  309. // level of the output.
  310. if (!has("json-stringify")) {
  311. // Internal: A map of control characters and their escaped equivalents.
  312. var Escapes = {
  313. 92: "\\\\",
  314. 34: '\\"',
  315. 8: "\\b",
  316. 12: "\\f",
  317. 10: "\\n",
  318. 13: "\\r",
  319. 9: "\\t"
  320. };
  321. // Internal: Converts `value` into a zero-padded string such that its
  322. // length is at least equal to `width`. The `width` must be <= 6.
  323. var leadingZeroes = "000000";
  324. var toPaddedString = function (width, value) {
  325. // The `|| 0` expression is necessary to work around a bug in
  326. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  327. return (leadingZeroes + (value || 0)).slice(-width);
  328. };
  329. // Internal: Double-quotes a string `value`, replacing all ASCII control
  330. // characters (characters with code unit values between 0 and 31) with
  331. // their escaped equivalents. This is an implementation of the
  332. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  333. var unicodePrefix = "\\u00";
  334. var quote = function (value) {
  335. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  336. if (isLarge) {
  337. symbols = value.split("");
  338. }
  339. for (; index < length; index++) {
  340. var charCode = value.charCodeAt(index);
  341. // If the character is a control character, append its Unicode or
  342. // shorthand escape sequence; otherwise, append the character as-is.
  343. switch (charCode) {
  344. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  345. result += Escapes[charCode];
  346. break;
  347. default:
  348. if (charCode < 32) {
  349. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  350. break;
  351. }
  352. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  353. }
  354. }
  355. return result + '"';
  356. };
  357. // Internal: Recursively serializes an object. Implements the
  358. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  359. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  360. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  361. try {
  362. // Necessary for host object support.
  363. value = object[property];
  364. } catch (exception) {}
  365. if (typeof value == "object" && value) {
  366. className = getClass.call(value);
  367. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  368. if (value > -1 / 0 && value < 1 / 0) {
  369. // Dates are serialized according to the `Date#toJSON` method
  370. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  371. // for the ISO 8601 date time string format.
  372. if (getDay) {
  373. // Manually compute the year, month, date, hours, minutes,
  374. // seconds, and milliseconds if the `getUTC*` methods are
  375. // buggy. Adapted from @Yaffle's `date-shim` project.
  376. date = floor(value / 864e5);
  377. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  378. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  379. date = 1 + date - getDay(year, month);
  380. // The `time` value specifies the time within the day (see ES
  381. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  382. // to compute `A modulo B`, as the `%` operator does not
  383. // correspond to the `modulo` operation for negative numbers.
  384. time = (value % 864e5 + 864e5) % 864e5;
  385. // The hours, minutes, seconds, and milliseconds are obtained by
  386. // decomposing the time within the day. See section 15.9.1.10.
  387. hours = floor(time / 36e5) % 24;
  388. minutes = floor(time / 6e4) % 60;
  389. seconds = floor(time / 1e3) % 60;
  390. milliseconds = time % 1e3;
  391. } else {
  392. year = value.getUTCFullYear();
  393. month = value.getUTCMonth();
  394. date = value.getUTCDate();
  395. hours = value.getUTCHours();
  396. minutes = value.getUTCMinutes();
  397. seconds = value.getUTCSeconds();
  398. milliseconds = value.getUTCMilliseconds();
  399. }
  400. // Serialize extended years correctly.
  401. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  402. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  403. // Months, dates, hours, minutes, and seconds should have two
  404. // digits; milliseconds should have three.
  405. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  406. // Milliseconds are optional in ES 5.0, but required in 5.1.
  407. "." + toPaddedString(3, milliseconds) + "Z";
  408. } else {
  409. value = null;
  410. }
  411. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  412. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  413. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  414. // ignores all `toJSON` methods on these objects unless they are
  415. // defined directly on an instance.
  416. value = value.toJSON(property);
  417. }
  418. }
  419. if (callback) {
  420. // If a replacement function was provided, call it to obtain the value
  421. // for serialization.
  422. value = callback.call(object, property, value);
  423. }
  424. if (value === null) {
  425. return "null";
  426. }
  427. className = getClass.call(value);
  428. if (className == booleanClass) {
  429. // Booleans are represented literally.
  430. return "" + value;
  431. } else if (className == numberClass) {
  432. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  433. // `"null"`.
  434. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  435. } else if (className == stringClass) {
  436. // Strings are double-quoted and escaped.
  437. return quote("" + value);
  438. }
  439. // Recursively serialize objects and arrays.
  440. if (typeof value == "object") {
  441. // Check for cyclic structures. This is a linear search; performance
  442. // is inversely proportional to the number of unique nested objects.
  443. for (length = stack.length; length--;) {
  444. if (stack[length] === value) {
  445. // Cyclic structures cannot be serialized by `JSON.stringify`.
  446. throw TypeError();
  447. }
  448. }
  449. // Add the object to the stack of traversed objects.
  450. stack.push(value);
  451. results = [];
  452. // Save the current indentation level and indent one additional level.
  453. prefix = indentation;
  454. indentation += whitespace;
  455. if (className == arrayClass) {
  456. // Recursively serialize array elements.
  457. for (index = 0, length = value.length; index < length; index++) {
  458. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  459. results.push(element === undef ? "null" : element);
  460. }
  461. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  462. } else {
  463. // Recursively serialize object members. Members are selected from
  464. // either a user-specified list of property names, or the object
  465. // itself.
  466. forEach(properties || value, function (property) {
  467. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  468. if (element !== undef) {
  469. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  470. // is not the empty string, let `member` {quote(property) + ":"}
  471. // be the concatenation of `member` and the `space` character."
  472. // The "`space` character" refers to the literal space
  473. // character, not the `space` {width} argument provided to
  474. // `JSON.stringify`.
  475. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  476. }
  477. });
  478. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  479. }
  480. // Remove the object from the traversed object stack.
  481. stack.pop();
  482. return result;
  483. }
  484. };
  485. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  486. JSON3.stringify = function (source, filter, width) {
  487. var whitespace, callback, properties, className;
  488. if (typeof filter == "function" || typeof filter == "object" && filter) {
  489. if ((className = getClass.call(filter)) == functionClass) {
  490. callback = filter;
  491. } else if (className == arrayClass) {
  492. // Convert the property names array into a makeshift set.
  493. properties = {};
  494. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  495. }
  496. }
  497. if (width) {
  498. if ((className = getClass.call(width)) == numberClass) {
  499. // Convert the `width` to an integer and create a string containing
  500. // `width` number of space characters.
  501. if ((width -= width % 1) > 0) {
  502. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  503. }
  504. } else if (className == stringClass) {
  505. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  506. }
  507. }
  508. // Opera <= 7.54u2 discards the values associated with empty string keys
  509. // (`""`) only if they are used directly within an object member list
  510. // (e.g., `!("" in { "": 1})`).
  511. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  512. };
  513. }
  514. // Public: Parses a JSON source string.
  515. if (!has("json-parse")) {
  516. var fromCharCode = String.fromCharCode;
  517. // Internal: A map of escaped control characters and their unescaped
  518. // equivalents.
  519. var Unescapes = {
  520. 92: "\\",
  521. 34: '"',
  522. 47: "/",
  523. 98: "\b",
  524. 116: "\t",
  525. 110: "\n",
  526. 102: "\f",
  527. 114: "\r"
  528. };
  529. // Internal: Stores the parser state.
  530. var Index, Source;
  531. // Internal: Resets the parser state and throws a `SyntaxError`.
  532. var abort = function() {
  533. Index = Source = null;
  534. throw SyntaxError();
  535. };
  536. // Internal: Returns the next token, or `"$"` if the parser has reached
  537. // the end of the source string. A token may be a string, number, `null`
  538. // literal, or Boolean literal.
  539. var lex = function () {
  540. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  541. while (Index < length) {
  542. charCode = source.charCodeAt(Index);
  543. switch (charCode) {
  544. case 9: case 10: case 13: case 32:
  545. // Skip whitespace tokens, including tabs, carriage returns, line
  546. // feeds, and space characters.
  547. Index++;
  548. break;
  549. case 123: case 125: case 91: case 93: case 58: case 44:
  550. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  551. // the current position.
  552. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  553. Index++;
  554. return value;
  555. case 34:
  556. // `"` delimits a JSON string; advance to the next character and
  557. // begin parsing the string. String tokens are prefixed with the
  558. // sentinel `@` character to distinguish them from punctuators and
  559. // end-of-string tokens.
  560. for (value = "@", Index++; Index < length;) {
  561. charCode = source.charCodeAt(Index);
  562. if (charCode < 32) {
  563. // Unescaped ASCII control characters (those with a code unit
  564. // less than the space character) are not permitted.
  565. abort();
  566. } else if (charCode == 92) {
  567. // A reverse solidus (`\`) marks the beginning of an escaped
  568. // control character (including `"`, `\`, and `/`) or Unicode
  569. // escape sequence.
  570. charCode = source.charCodeAt(++Index);
  571. switch (charCode) {
  572. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  573. // Revive escaped control characters.
  574. value += Unescapes[charCode];
  575. Index++;
  576. break;
  577. case 117:
  578. // `\u` marks the beginning of a Unicode escape sequence.
  579. // Advance to the first character and validate the
  580. // four-digit code point.
  581. begin = ++Index;
  582. for (position = Index + 4; Index < position; Index++) {
  583. charCode = source.charCodeAt(Index);
  584. // A valid sequence comprises four hexdigits (case-
  585. // insensitive) that form a single hexadecimal value.
  586. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  587. // Invalid Unicode escape sequence.
  588. abort();
  589. }
  590. }
  591. // Revive the escaped character.
  592. value += fromCharCode("0x" + source.slice(begin, Index));
  593. break;
  594. default:
  595. // Invalid escape sequence.
  596. abort();
  597. }
  598. } else {
  599. if (charCode == 34) {
  600. // An unescaped double-quote character marks the end of the
  601. // string.
  602. break;
  603. }
  604. charCode = source.charCodeAt(Index);
  605. begin = Index;
  606. // Optimize for the util case where a string is valid.
  607. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  608. charCode = source.charCodeAt(++Index);
  609. }
  610. // Append the string as-is.
  611. value += source.slice(begin, Index);
  612. }
  613. }
  614. if (source.charCodeAt(Index) == 34) {
  615. // Advance to the next character and return the revived string.
  616. Index++;
  617. return value;
  618. }
  619. // Unterminated string.
  620. abort();
  621. default:
  622. // Parse numbers and literals.
  623. begin = Index;
  624. // Advance past the negative sign, if one is specified.
  625. if (charCode == 45) {
  626. isSigned = true;
  627. charCode = source.charCodeAt(++Index);
  628. }
  629. // Parse an integer or floating-point value.
  630. if (charCode >= 48 && charCode <= 57) {
  631. // Leading zeroes are interpreted as octal literals.
  632. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  633. // Illegal octal literal.
  634. abort();
  635. }
  636. isSigned = false;
  637. // Parse the integer component.
  638. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  639. // Floats cannot contain a leading decimal point; however, this
  640. // case is already accounted for by the parser.
  641. if (source.charCodeAt(Index) == 46) {
  642. position = ++Index;
  643. // Parse the decimal component.
  644. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  645. if (position == Index) {
  646. // Illegal trailing decimal.
  647. abort();
  648. }
  649. Index = position;
  650. }
  651. // Parse exponents. The `e` denoting the exponent is
  652. // case-insensitive.
  653. charCode = source.charCodeAt(Index);
  654. if (charCode == 101 || charCode == 69) {
  655. charCode = source.charCodeAt(++Index);
  656. // Skip past the sign following the exponent, if one is
  657. // specified.
  658. if (charCode == 43 || charCode == 45) {
  659. Index++;
  660. }
  661. // Parse the exponential component.
  662. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  663. if (position == Index) {
  664. // Illegal empty exponent.
  665. abort();
  666. }
  667. Index = position;
  668. }
  669. // Coerce the parsed value to a JavaScript number.
  670. return +source.slice(begin, Index);
  671. }
  672. // A negative sign may only precede numbers.
  673. if (isSigned) {
  674. abort();
  675. }
  676. // `true`, `false`, and `null` literals.
  677. if (source.slice(Index, Index + 4) == "true") {
  678. Index += 4;
  679. return true;
  680. } else if (source.slice(Index, Index + 5) == "false") {
  681. Index += 5;
  682. return false;
  683. } else if (source.slice(Index, Index + 4) == "null") {
  684. Index += 4;
  685. return null;
  686. }
  687. // Unrecognized token.
  688. abort();
  689. }
  690. }
  691. // Return the sentinel `$` character if the parser has reached the end
  692. // of the source string.
  693. return "$";
  694. };
  695. // Internal: Parses a JSON `value` token.
  696. var get = function (value) {
  697. var results, hasMembers;
  698. if (value == "$") {
  699. // Unexpected end of input.
  700. abort();
  701. }
  702. if (typeof value == "string") {
  703. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  704. // Remove the sentinel `@` character.
  705. return value.slice(1);
  706. }
  707. // Parse object and array literals.
  708. if (value == "[") {
  709. // Parses a JSON array, returning a new JavaScript array.
  710. results = [];
  711. for (;; hasMembers || (hasMembers = true)) {
  712. value = lex();
  713. // A closing square bracket marks the end of the array literal.
  714. if (value == "]") {
  715. break;
  716. }
  717. // If the array literal contains elements, the current token
  718. // should be a comma separating the previous element from the
  719. // next.
  720. if (hasMembers) {
  721. if (value == ",") {
  722. value = lex();
  723. if (value == "]") {
  724. // Unexpected trailing `,` in array literal.
  725. abort();
  726. }
  727. } else {
  728. // A `,` must separate each array element.
  729. abort();
  730. }
  731. }
  732. // Elisions and leading commas are not permitted.
  733. if (value == ",") {
  734. abort();
  735. }
  736. results.push(get(value));
  737. }
  738. return results;
  739. } else if (value == "{") {
  740. // Parses a JSON object, returning a new JavaScript object.
  741. results = {};
  742. for (;; hasMembers || (hasMembers = true)) {
  743. value = lex();
  744. // A closing curly brace marks the end of the object literal.
  745. if (value == "}") {
  746. break;
  747. }
  748. // If the object literal contains members, the current token
  749. // should be a comma separator.
  750. if (hasMembers) {
  751. if (value == ",") {
  752. value = lex();
  753. if (value == "}") {
  754. // Unexpected trailing `,` in object literal.
  755. abort();
  756. }
  757. } else {
  758. // A `,` must separate each object member.
  759. abort();
  760. }
  761. }
  762. // Leading commas are not permitted, object property names must be
  763. // double-quoted strings, and a `:` must separate each property
  764. // name and value.
  765. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  766. abort();
  767. }
  768. results[value.slice(1)] = get(lex());
  769. }
  770. return results;
  771. }
  772. // Unexpected token encountered.
  773. abort();
  774. }
  775. return value;
  776. };
  777. // Internal: Updates a traversed object member.
  778. var update = function(source, property, callback) {
  779. var element = walk(source, property, callback);
  780. if (element === undef) {
  781. delete source[property];
  782. } else {
  783. source[property] = element;
  784. }
  785. };
  786. // Internal: Recursively traverses a parsed JSON object, invoking the
  787. // `callback` function for each value. This is an implementation of the
  788. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  789. var walk = function (source, property, callback) {
  790. var value = source[property], length;
  791. if (typeof value == "object" && value) {
  792. // `forEach` can't be used to traverse an array in Opera <= 8.54
  793. // because its `Object#hasOwnProperty` implementation returns `false`
  794. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  795. if (getClass.call(value) == arrayClass) {
  796. for (length = value.length; length--;) {
  797. update(value, length, callback);
  798. }
  799. } else {
  800. forEach(value, function (property) {
  801. update(value, property, callback);
  802. });
  803. }
  804. }
  805. return callback.call(source, property, value);
  806. };
  807. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  808. JSON3.parse = function (source, callback) {
  809. var result, value;
  810. Index = 0;
  811. Source = "" + source;
  812. result = get(lex());
  813. // If a JSON string contains multiple tokens, it is invalid.
  814. if (lex() != "$") {
  815. abort();
  816. }
  817. // Reset the parser state.
  818. Index = Source = null;
  819. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  820. };
  821. }
  822. }
  823. // Export for asynchronous module loaders.
  824. if (isLoader) {
  825. define(function () {
  826. return JSON3;
  827. });
  828. }
  829. }(this));