circular-json.node.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*!
  2. Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. var
  20. // should be a not so common char
  21. // possibly one JSON does not encode
  22. // possibly one encodeURIComponent does not encode
  23. // right now this char is '~' but this might change in the future
  24. specialChar = '~',
  25. safeSpecialChar = '\\x' + (
  26. '0' + specialChar.charCodeAt(0).toString(16)
  27. ).slice(-2),
  28. escapedSafeSpecialChar = '\\' + safeSpecialChar,
  29. specialCharRG = new RegExp(safeSpecialChar, 'g'),
  30. safeSpecialCharRG = new RegExp(escapedSafeSpecialChar, 'g'),
  31. safeStartWithSpecialCharRG = new RegExp('(?:^|([^\\\\]))' + escapedSafeSpecialChar),
  32. indexOf = [].indexOf || function(v){
  33. for(var i=this.length;i--&&this[i]!==v;);
  34. return i;
  35. },
  36. $String = String // there's no way to drop warnings in JSHint
  37. // about new String ... well, I need that here!
  38. // faked, and happy linter!
  39. ;
  40. function generateReplacer(value, replacer, resolve) {
  41. var
  42. doNotIgnore = false,
  43. inspect = !!replacer,
  44. path = [],
  45. all = [value],
  46. seen = [value],
  47. mapp = [resolve ? specialChar : '[Circular]'],
  48. last = value,
  49. lvl = 1,
  50. i, fn
  51. ;
  52. if (inspect) {
  53. fn = typeof replacer === 'object' ?
  54. function (key, value) {
  55. return key !== '' && replacer.indexOf(key) < 0 ? void 0 : value;
  56. } :
  57. replacer;
  58. }
  59. return function(key, value) {
  60. // the replacer has rights to decide
  61. // if a new object should be returned
  62. // or if there's some key to drop
  63. // let's call it here rather than "too late"
  64. if (inspect) value = fn.call(this, key, value);
  65. // first pass should be ignored, since it's just the initial object
  66. if (doNotIgnore) {
  67. if (last !== this) {
  68. i = lvl - indexOf.call(all, this) - 1;
  69. lvl -= i;
  70. all.splice(lvl, all.length);
  71. path.splice(lvl - 1, path.length);
  72. last = this;
  73. }
  74. // console.log(lvl, key, path);
  75. if (typeof value === 'object' && value) {
  76. // if object isn't referring to parent object, add to the
  77. // object path stack. Otherwise it is already there.
  78. if (indexOf.call(all, value) < 0) {
  79. all.push(last = value);
  80. }
  81. lvl = all.length;
  82. i = indexOf.call(seen, value);
  83. if (i < 0) {
  84. i = seen.push(value) - 1;
  85. if (resolve) {
  86. // key cannot contain specialChar but could be not a string
  87. path.push(('' + key).replace(specialCharRG, safeSpecialChar));
  88. mapp[i] = specialChar + path.join(specialChar);
  89. } else {
  90. mapp[i] = mapp[0];
  91. }
  92. } else {
  93. value = mapp[i];
  94. }
  95. } else {
  96. if (typeof value === 'string' && resolve) {
  97. // ensure no special char involved on deserialization
  98. // in this case only first char is important
  99. // no need to replace all value (better performance)
  100. value = value .replace(safeSpecialChar, escapedSafeSpecialChar)
  101. .replace(specialChar, safeSpecialChar);
  102. }
  103. }
  104. } else {
  105. doNotIgnore = true;
  106. }
  107. return value;
  108. };
  109. }
  110. function retrieveFromPath(current, keys) {
  111. for(var i = 0, length = keys.length; i < length; current = current[
  112. // keys should be normalized back here
  113. keys[i++].replace(safeSpecialCharRG, specialChar)
  114. ]);
  115. return current;
  116. }
  117. function generateReviver(reviver) {
  118. return function(key, value) {
  119. var isString = typeof value === 'string';
  120. if (isString && value.charAt(0) === specialChar) {
  121. return new $String(value.slice(1));
  122. }
  123. if (key === '') value = regenerate(value, value, {});
  124. // again, only one needed, do not use the RegExp for this replacement
  125. // only keys need the RegExp
  126. if (isString) value = value .replace(safeStartWithSpecialCharRG, '$1' + specialChar)
  127. .replace(escapedSafeSpecialChar, safeSpecialChar);
  128. return reviver ? reviver.call(this, key, value) : value;
  129. };
  130. }
  131. function regenerateArray(root, current, retrieve) {
  132. for (var i = 0, length = current.length; i < length; i++) {
  133. current[i] = regenerate(root, current[i], retrieve);
  134. }
  135. return current;
  136. }
  137. function regenerateObject(root, current, retrieve) {
  138. for (var key in current) {
  139. if (current.hasOwnProperty(key)) {
  140. current[key] = regenerate(root, current[key], retrieve);
  141. }
  142. }
  143. return current;
  144. }
  145. function regenerate(root, current, retrieve) {
  146. return current instanceof Array ?
  147. // fast Array reconstruction
  148. regenerateArray(root, current, retrieve) :
  149. (
  150. current instanceof $String ?
  151. (
  152. // root is an empty string
  153. current.length ?
  154. (
  155. retrieve.hasOwnProperty(current) ?
  156. retrieve[current] :
  157. retrieve[current] = retrieveFromPath(
  158. root, current.split(specialChar)
  159. )
  160. ) :
  161. root
  162. ) :
  163. (
  164. current instanceof Object ?
  165. // dedicated Object parser
  166. regenerateObject(root, current, retrieve) :
  167. // value as it is
  168. current
  169. )
  170. )
  171. ;
  172. }
  173. var CircularJSON = {
  174. stringify: function stringify(value, replacer, space, doNotResolve) {
  175. return CircularJSON.parser.stringify(
  176. value,
  177. generateReplacer(value, replacer, !doNotResolve),
  178. space
  179. );
  180. },
  181. parse: function parse(text, reviver) {
  182. return CircularJSON.parser.parse(
  183. text,
  184. generateReviver(reviver)
  185. );
  186. },
  187. // A parser should be an API 1:1 compatible with JSON
  188. // it should expose stringify and parse methods.
  189. // The default parser is the native JSON.
  190. parser: JSON
  191. };
  192. module.exports = CircularJSON;