fork download
  1. <!DOCTYPE html>
  2. <script>
  3. 'use strict'
  4.  
  5. Object.isObject = Object.isObject || function isObject(obj) { return !!obj && typeof obj == 'object' }
  6.  
  7.  
  8.  
  9. function byXJSON(xjson) {
  10.  
  11.  
  12. var refs = JSON.parse(xjson)
  13.  
  14.  
  15. var vals = refs.map(function (ref) {
  16. return typeof ref == 'object' ? {} : ref
  17. })
  18.  
  19. refs.reduceRight(function (goo ,ref, id) {
  20. if (!Object.isObject(ref)) return
  21. Object.keys(ref).forEach(function (key) {
  22. vals[id][key] = vals[ref[key]]
  23. })
  24. }, void 0)
  25.  
  26. return vals[0]
  27.  
  28. }
  29.  
  30.  
  31.  
  32. function toXJSON(obj, full) {
  33.  
  34. var refs = []
  35. var vals = []
  36.  
  37. conv(obj, 0)
  38.  
  39.  
  40. function conv(obj, id) {
  41.  
  42. vals[id] = obj
  43. var ref = refs[id] = {}
  44. var keys = full ? Object.getOwnPropertyNames(obj) : Object.keys(obj)
  45.  
  46. keys.forEach(function (key) {
  47. var val = obj[key]
  48.  
  49. var id = vals.indexOf(val)
  50.  
  51. if (id != -1) {
  52. ref[key] = id
  53. return
  54. }
  55.  
  56. id = vals.length
  57. ref[key] = id
  58.  
  59. if (Object.isObject(val)) {
  60. conv(val, id)
  61. } else {
  62. vals[id] = val
  63. refs[id] = val
  64. }
  65.  
  66. })
  67.  
  68. }
  69.  
  70.  
  71. chkCir(refs) //循環参照をチェック
  72.  
  73. return JSON.stringify(refs)
  74.  
  75. }
  76.  
  77.  
  78.  
  79. function chkCir(refs) {
  80. refs.forEach(function (ref, i) {
  81. if (!Object.isObject(ref)) return
  82. Object.keys(ref).forEach(function (key) {
  83. if (Object.isObject(ref[key])) console.log('chkerr', i, key)
  84. })
  85. })
  86. }
  87.  
  88.  
  89.  
  90. function test(id, obj, full) {
  91.  
  92. console.group('test ' + id)
  93. var xjson = toXJSON(obj, full)
  94. var xobj = byXJSON(xjson)
  95. console.log(xjson)
  96. console.dir(xobj)
  97. console.dir(obj)
  98. console.groupEnd('test ' + id)
  99.  
  100. }
  101.  
  102.  
  103. function testing() {
  104. var obj1 = {
  105. a: {
  106. b: {
  107. c: {},
  108. d: 'xyz',
  109. e: {}
  110. },
  111. f: 123,
  112. },
  113. g: [0,1,2,3]
  114. }
  115.  
  116. obj1.a.b.c = obj1
  117. obj1.a.b.e = obj1.a
  118.  
  119.  
  120. test(1, obj1)
  121. test(2, Math, true)
  122. test(3, window)
  123.  
  124. }
  125.  
  126.  
  127. window.onload = testing
  128.  
  129. </script>
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty