JSON.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * JSON.js
  3. *
  4. * Copyright, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://www.tinymce.com/license
  8. * Contributing: http://www.tinymce.com/contributing
  9. */
  10. /**
  11. * JSON parser and serializer class.
  12. *
  13. * @class tinymce.util.JSON
  14. * @static
  15. * @example
  16. * // JSON parse a string into an object
  17. * var obj = tinymce.util.JSON.parse(somestring);
  18. *
  19. * // JSON serialize a object into an string
  20. * var str = tinymce.util.JSON.serialize(obj);
  21. */
  22. define("tinymce/util/JSON", [], function() {
  23. function serialize(o, quote) {
  24. var i, v, t, name;
  25. quote = quote || '"';
  26. if (o === null) {
  27. return 'null';
  28. }
  29. t = typeof o;
  30. if (t == 'string') {
  31. v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
  32. return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
  33. // Make sure single quotes never get encoded inside double quotes for JSON compatibility
  34. if (quote === '"' && a === "'") {
  35. return a;
  36. }
  37. i = v.indexOf(b);
  38. if (i + 1) {
  39. return '\\' + v.charAt(i + 1);
  40. }
  41. a = b.charCodeAt().toString(16);
  42. return '\\u' + '0000'.substring(a.length) + a;
  43. }) + quote;
  44. }
  45. if (t == 'object') {
  46. if (o.hasOwnProperty && Object.prototype.toString.call(o) === '[object Array]') {
  47. for (i = 0, v = '['; i < o.length; i++) {
  48. v += (i > 0 ? ',' : '') + serialize(o[i], quote);
  49. }
  50. return v + ']';
  51. }
  52. v = '{';
  53. for (name in o) {
  54. if (o.hasOwnProperty(name)) {
  55. v += typeof o[name] != 'function' ? (v.length > 1 ? ',' + quote : quote) + name +
  56. quote + ':' + serialize(o[name], quote) : '';
  57. }
  58. }
  59. return v + '}';
  60. }
  61. return '' + o;
  62. }
  63. return {
  64. /**
  65. * Serializes the specified object as a JSON string.
  66. *
  67. * @method serialize
  68. * @param {Object} obj Object to serialize as a JSON string.
  69. * @param {String} quote Optional quote string defaults to ".
  70. * @return {string} JSON string serialized from input.
  71. */
  72. serialize: serialize,
  73. /**
  74. * Unserializes/parses the specified JSON string into a object.
  75. *
  76. * @method parse
  77. * @param {string} s JSON String to parse into a JavaScript object.
  78. * @return {Object} Object from input JSON string or undefined if it failed.
  79. */
  80. parse: function(text) {
  81. try {
  82. // Trick uglify JS
  83. return window[String.fromCharCode(101) + 'val']('(' + text + ')');
  84. } catch (ex) {
  85. // Ignore
  86. }
  87. }
  88. /**#@-*/
  89. };
  90. });