/branches/jsdoc_tk_gui/setup/workingDirectory/Webeo/ao/data/Json.js

http://jsdoc-toolkit.googlecode.com/ · JavaScript · 121 lines · 97 code · 3 blank · 21 comment · 14 complexity · 6c701934b40673a39041dead9d68364f MD5 · raw file

  1. ek.register("ao.data.Json");
  2. /*
  3. json.js
  4. 2006-04-28
  5. This file adds these methods to JavaScript:
  6. object.toJSONString()
  7. This method produces a JSON text from an object. The
  8. object must not contain any cyclical references.
  9. array.toJSONString()
  10. This method produces a JSON text from an array. The
  11. array must not contain any cyclical references.
  12. string.parseJSON()
  13. This method parses a JSON text to produce an object or
  14. array. It will return false if there is an error.
  15. */
  16. (function () {
  17. var m = {
  18. '\b': '\\b',
  19. '\t': '\\t',
  20. '\n': '\\n',
  21. '\f': '\\f',
  22. '\r': '\\r',
  23. '"' : '\\"',
  24. '\\': '\\\\'
  25. },
  26. s = {
  27. array: function (x) {
  28. var a = ['['], b, f, i, l = x.length, v;
  29. for (i = 0; i < l; i += 1) {
  30. v = x[i];
  31. f = s[typeof v];
  32. if (f) {
  33. v = f(v);
  34. if (typeof v == 'string') {
  35. if (b) {
  36. a[a.length] = ',';
  37. }
  38. a[a.length] = v;
  39. b = true;
  40. }
  41. }
  42. }
  43. a[a.length] = ']';
  44. return a.join('');
  45. },
  46. 'boolean': function (x) {
  47. return String(x);
  48. },
  49. 'null': function (x) {
  50. return "null";
  51. },
  52. number: function (x) {
  53. return isFinite(x) ? String(x) : 'null';
  54. },
  55. object: function (x) {
  56. if (x) {
  57. if (x instanceof Array) {
  58. return s.array(x);
  59. }
  60. var a = ['{'], b, f, i, v;
  61. for (i in x) {
  62. v = x[i];
  63. f = s[typeof v];
  64. if (f) {
  65. v = f(v);
  66. if (typeof v == 'string') {
  67. if (b) {
  68. a[a.length] = ',';
  69. }
  70. a.push(s.string(i), ':', v);
  71. b = true;
  72. }
  73. }
  74. }
  75. a[a.length] = '}';
  76. return a.join('');
  77. }
  78. return 'null';
  79. },
  80. string: function (x) {
  81. if (/["\\\x00-\x1f]/.test(x)) {
  82. x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
  83. var c = m[b];
  84. if (c) {
  85. return c;
  86. }
  87. c = b.charCodeAt();
  88. return '\\u00' +
  89. Math.floor(c / 16).toString(16) +
  90. (c % 16).toString(16);
  91. });
  92. }
  93. return '"' + x + '"';
  94. }
  95. };
  96. Object.prototype.toJSONString = function () {
  97. return s.object(this);
  98. };
  99. Array.prototype.toJSONString = function () {
  100. return s.array(this);
  101. };
  102. })();
  103. String.prototype.parseJSON = function () {
  104. try {
  105. return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
  106. this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
  107. eval('(' + this + ')');
  108. } catch (e) {
  109. return false;
  110. }
  111. };