circular-json.max.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 CircularJSON = (function(JSON, RegExp){
  20. var
  21. // should be a not so common char
  22. // possibly one JSON does not encode
  23. // possibly one encodeURIComponent does not encode
  24. // right now this char is '~' but this might change in the future
  25. specialChar = '~',
  26. safeSpecialChar = '\\x' + (
  27. '0' + specialChar.charCodeAt(0).toString(16)
  28. ).slice(-2),
  29. escapedSafeSpecialChar = '\\' + safeSpecialChar,
  30. specialCharRG = new RegExp(safeSpecialChar, 'g'),
  31. safeSpecialCharRG = new RegExp(escapedSafeSpecialChar, 'g'),
  32. safeStartWithSpecialCharRG = new RegExp('(?:^|([^\\\\]))' + escapedSafeSpecialChar),
  33. indexOf = [].indexOf || function(v){
  34. for(var i=this.length;i--&&this[i]!==v;);
  35. return i;
  36. },
  37. $String = String // there's no way to drop warnings in JSHint
  38. // about new String ... well, I need that here!
  39. // faked, and happy linter!
  40. ;
  41. function generateReplacer(value, replacer, resolve) {
  42. var
  43. doNotIgnore = false,
  44. inspect = !!replacer,
  45. path = [],
  46. all = [value],
  47. seen = [value],
  48. mapp = [resolve ? specialChar : '[Circular]'],
  49. last = value,
  50. lvl = 1,
  51. i, fn
  52. ;
  53. if (inspect) {
  54. fn = typeof replacer === 'object' ?
  55. function (key, value) {
  56. return key !== '' && replacer.indexOf(key) < 0 ? void 0 : value;
  57. } :
  58. replacer;
  59. }
  60. return function(key, value) {
  61. // the replacer has rights to decide
  62. // if a new object should be returned
  63. // or if there's some key to drop
  64. // let's call it here rather than "too late"
  65. if (inspect) value = fn.call(this, key, value);
  66. // first pass should be ignored, since it's just the initial object
  67. if (doNotIgnore) {
  68. if (last !== this) {
  69. i = lvl - indexOf.call(all, this) - 1;
  70. lvl -= i;
  71. all.splice(lvl, all.length);
  72. path.splice(lvl - 1, path.length);
  73. last = this;
  74. }
  75. // console.log(lvl, key, path);
  76. if (typeof value === 'object' && value) {
  77. // if object isn't referring to parent object, add to the
  78. // object path stack. Otherwise it is already there.
  79. if (indexOf.call(all, value) < 0) {
  80. all.push(last = value);
  81. }
  82. lvl = all.length;
  83. i = indexOf.call(seen, value);
  84. if (i < 0) {
  85. i = seen.push(value) - 1;
  86. if (resolve) {
  87. // key cannot contain specialChar but could be not a string
  88. path.push(('' + key).replace(specialCharRG, safeSpecialChar));
  89. mapp[i] = specialChar + path.join(specialChar);
  90. } else {
  91. mapp[i] = mapp[0];
  92. }
  93. } else {
  94. value = mapp[i];
  95. }
  96. } else {
  97. if (typeof value === 'string' && resolve) {
  98. // ensure no special char involved on deserialization
  99. // in this case only first char is important
  100. // no need to replace all value (better performance)
  101. value = value .replace(safeSpecialChar, escapedSafeSpecialChar)
  102. .replace(specialChar, safeSpecialChar);
  103. }
  104. }
  105. } else {
  106. doNotIgnore = true;
  107. }
  108. return value;
  109. };
  110. }
  111. function retrieveFromPath(current, keys) {
  112. for(var i = 0, length = keys.length; i < length; current = current[
  113. // keys should be normalized back here
  114. keys[i++].replace(safeSpecialCharRG, specialChar)
  115. ]);
  116. return current;
  117. }
  118. function generateReviver(reviver) {
  119. return function(key, value) {
  120. var isString = typeof value === 'string';
  121. if (isString && value.charAt(0) === specialChar) {
  122. return new $String(value.slice(1));
  123. }
  124. if (key === '') value = regenerate(value, value, {});
  125. // again, only one needed, do not use the RegExp for this replacement
  126. // only keys need the RegExp
  127. if (isString) value = value .replace(safeStartWithSpecialCharRG, '$1' + specialChar)
  128. .replace(escapedSafeSpecialChar, safeSpecialChar);
  129. return reviver ? reviver.call(this, key, value) : value;
  130. };
  131. }
  132. function regenerateArray(root, current, retrieve) {
  133. for (var i = 0, length = current.length; i < length; i++) {
  134. current[i] = regenerate(root, current[i], retrieve);
  135. }
  136. return current;
  137. }
  138. function regenerateObject(root, current, retrieve) {
  139. for (var key in current) {
  140. if (current.hasOwnProperty(key)) {
  141. current[key] = regenerate(root, current[key], retrieve);
  142. }
  143. }
  144. return current;
  145. }
  146. function regenerate(root, current, retrieve) {
  147. return current instanceof Array ?
  148. // fast Array reconstruction
  149. regenerateArray(root, current, retrieve) :
  150. (
  151. current instanceof $String ?
  152. (
  153. // root is an empty string
  154. current.length ?
  155. (
  156. retrieve.hasOwnProperty(current) ?
  157. retrieve[current] :
  158. retrieve[current] = retrieveFromPath(
  159. root, current.split(specialChar)
  160. )
  161. ) :
  162. root
  163. ) :
  164. (
  165. current instanceof Object ?
  166. // dedicated Object parser
  167. regenerateObject(root, current, retrieve) :
  168. // value as it is
  169. current
  170. )
  171. )
  172. ;
  173. }
  174. var CircularJSON = {
  175. stringify: function stringify(value, replacer, space, doNotResolve) {
  176. return CircularJSON.parser.stringify(
  177. value,
  178. generateReplacer(value, replacer, !doNotResolve),
  179. space
  180. );
  181. },
  182. parse: function parse(text, reviver) {
  183. return CircularJSON.parser.parse(
  184. text,
  185. generateReviver(reviver)
  186. );
  187. },
  188. // A parser should be an API 1:1 compatible with JSON
  189. // it should expose stringify and parse methods.
  190. // The default parser is the native JSON.
  191. parser: JSON
  192. };
  193. return CircularJSON;
  194. }(JSON, RegExp));