jquery.tojson.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (function ($) {
  2. m = {
  3. '\b': '\\b',
  4. '\t': '\\t',
  5. '\n': '\\n',
  6. '\f': '\\f',
  7. '\r': '\\r',
  8. '"' : '\\"',
  9. '\\': '\\\\'
  10. },
  11. $.toJSON = function (value, whitelist) {
  12. var a, // The array holding the partial texts.
  13. i, // The loop counter.
  14. k, // The member key.
  15. l, // Length.
  16. r = /["\\\x00-\x1f\x7f-\x9f]/g,
  17. v; // The member value.
  18. switch (typeof value) {
  19. case 'string':
  20. return r.test(value) ?
  21. '"' + value.replace(r, function (a) {
  22. var c = m[a];
  23. if (c) {
  24. return c;
  25. }
  26. c = a.charCodeAt();
  27. return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
  28. }) + '"' :
  29. '"' + value + '"';
  30. case 'number':
  31. return isFinite(value) ? String(value) : 'null';
  32. case 'boolean':
  33. case 'null':
  34. return String(value);
  35. case 'object':
  36. if (!value) {
  37. return 'null';
  38. }
  39. if (typeof value.toJSON === 'function') {
  40. return $.toJSON(value.toJSON());
  41. }
  42. a = [];
  43. if (typeof value.length === 'number' &&
  44. !(value.propertyIsEnumerable('length'))) {
  45. l = value.length;
  46. for (i = 0; i < l; i += 1) {
  47. a.push($.toJSON(value[i], whitelist) || 'null');
  48. }
  49. return '[' + a.join(',') + ']';
  50. }
  51. if (whitelist) {
  52. l = whitelist.length;
  53. for (i = 0; i < l; i += 1) {
  54. k = whitelist[i];
  55. if (typeof k === 'string') {
  56. v = $.toJSON(value[k], whitelist);
  57. if (v) {
  58. a.push($.toJSON(k) + ':' + v);
  59. }
  60. }
  61. }
  62. } else {
  63. for (k in value) {
  64. if (typeof k === 'string') {
  65. v = $.toJSON(value[k], whitelist);
  66. if (v) {
  67. a.push($.toJSON(k) + ':' + v);
  68. }
  69. }
  70. }
  71. }
  72. return '{' + a.join(',') + '}';
  73. }
  74. };
  75. })(jQuery);