/functions/json/json_encode.js

https://github.com/camille-hdl/phpjs
JavaScript | 166 lines | 102 code | 17 blank | 47 comment | 19 complexity | f4f158c64bdb205b3d1fb646ed4dadd5 MD5 | raw file
  1. function json_encode(mixed_val) {
  2. // discuss at: http://phpjs.org/functions/json_encode/
  3. // original by: Public Domain (http://www.json.org/json2.js)
  4. // reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  5. // improved by: Michael White
  6. // input by: felix
  7. // bugfixed by: Brett Zamir (http://brett-zamir.me)
  8. // example 1: json_encode('Kevin');
  9. // returns 1: '"Kevin"'
  10. /*
  11. http://www.JSON.org/json2.js
  12. 2008-11-19
  13. Public Domain.
  14. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  15. See http://www.JSON.org/js.html
  16. */
  17. var retVal, json = this.window.JSON;
  18. try {
  19. if (typeof json === 'object' && typeof json.stringify === 'function') {
  20. // Errors will not be caught here if our own equivalent to resource
  21. retVal = json.stringify(mixed_val);
  22. // (an instance of PHPJS_Resource) is used
  23. if (retVal === undefined) {
  24. throw new SyntaxError('json_encode');
  25. }
  26. return retVal;
  27. }
  28. var value = mixed_val;
  29. var quote = function (string) {
  30. var escapable =
  31. /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  32. var meta = {
  33. // table of character substitutions
  34. '\b': '\\b',
  35. '\t': '\\t',
  36. '\n': '\\n',
  37. '\f': '\\f',
  38. '\r': '\\r',
  39. '"': '\\"',
  40. '\\': '\\\\'
  41. };
  42. escapable.lastIndex = 0;
  43. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  44. var c = meta[a];
  45. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0)
  46. .toString(16))
  47. .slice(-4);
  48. }) + '"' : '"' + string + '"';
  49. };
  50. var str = function (key, holder) {
  51. var gap = '';
  52. var indent = ' ';
  53. // The loop counter.
  54. var i = 0;
  55. // The member key.
  56. var k = '';
  57. // The member value.
  58. var v = '';
  59. var length = 0;
  60. var mind = gap;
  61. var partial = [];
  62. var value = holder[key];
  63. // If the value has a toJSON method, call it to obtain a replacement value.
  64. if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
  65. value = value.toJSON(key);
  66. }
  67. // What happens next depends on the value's type.
  68. switch (typeof value) {
  69. case 'string':
  70. return quote(value);
  71. case 'number':
  72. // JSON numbers must be finite. Encode non-finite numbers as null.
  73. return isFinite(value) ? String(value) : 'null';
  74. case 'boolean':
  75. case 'null':
  76. // If the value is a boolean or null, convert it to a string. Note:
  77. // typeof null does not produce 'null'. The case is included here in
  78. // the remote chance that this gets fixed someday.
  79. return String(value);
  80. case 'object':
  81. // If the type is 'object', we might be dealing with an object or an array or
  82. // null.
  83. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  84. // so watch out for that case.
  85. if (!value) {
  86. return 'null';
  87. }
  88. if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) || (window.PHPJS_Resource &&
  89. value instanceof window.PHPJS_Resource)) {
  90. throw new SyntaxError('json_encode');
  91. }
  92. // Make an array to hold the partial results of stringifying this object value.
  93. gap += indent;
  94. partial = [];
  95. // Is the value an array?
  96. if (Object.prototype.toString.apply(value) === '[object Array]') {
  97. // The value is an array. Stringify every element. Use null as a placeholder
  98. // for non-JSON values.
  99. length = value.length;
  100. for (i = 0; i < length; i += 1) {
  101. partial[i] = str(i, value) || 'null';
  102. }
  103. // Join all of the elements together, separated with commas, and wrap them in
  104. // brackets.
  105. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind +
  106. ']' : '[' + partial.join(',') + ']';
  107. gap = mind;
  108. return v;
  109. }
  110. // Iterate through all of the keys in the object.
  111. for (k in value) {
  112. if (Object.hasOwnProperty.call(value, k)) {
  113. v = str(k, value);
  114. if (v) {
  115. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  116. }
  117. }
  118. }
  119. // Join all of the member texts together, separated with commas,
  120. // and wrap them in braces.
  121. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  122. '{' + partial.join(',') + '}';
  123. gap = mind;
  124. return v;
  125. case 'undefined':
  126. // Fall-through
  127. case 'function':
  128. // Fall-through
  129. default:
  130. throw new SyntaxError('json_encode');
  131. }
  132. };
  133. // Make a fake root object containing our value under the key of ''.
  134. // Return the result of stringifying the value.
  135. return str('', {
  136. '': value
  137. });
  138. } catch (err) {
  139. // Todo: ensure error handling above throws a SyntaxError in all cases where it could
  140. // (i.e., when the JSON global is not available and there is an error)
  141. if (!(err instanceof SyntaxError)) {
  142. throw new Error('Unexpected error type in json_encode()');
  143. }
  144. this.php_js = this.php_js || {};
  145. // usable by json_last_error()
  146. this.php_js.last_error_json = 4;
  147. return null;
  148. }
  149. }