fork download
  1. var XJSON = new function () {
  2.  
  3. function isPureObject(obj) { return !!obj && typeof obj == 'object' && !(obj instanceof Array)}
  4.  
  5.  
  6. this.parse = function (xjson) {
  7.  
  8. var refs = JSON.parse(xjson)
  9.  
  10. var vals = refs.map(function (ref) {
  11. return isPureObject(ref) ? {} : ref
  12. })
  13.  
  14. refs.reduceRight(function (_ ,ref, id) {
  15. if (!isPureObject(ref)) return
  16. Object.keys(ref).forEach(function (key) {
  17. vals[id][key] = vals[ref[key]]
  18. })
  19. }, undefined)
  20.  
  21. return vals[0]
  22.  
  23. }
  24.  
  25.  
  26. this.stringify = function (obj) {
  27.  
  28. var refs = [], vals = []
  29.  
  30.  
  31. function conv(obj, id) {
  32.  
  33. vals[id] = refs[id] = obj
  34. if (!isPureObject(obj)) return
  35. var ref = refs[id] = {}
  36.  
  37. Object.getOwnPropertyNames(obj).forEach(function (key) {
  38.  
  39. var val = obj[key]
  40. var id = ref[key] = vals.indexOf(val)
  41. if (id != -1) return
  42. var newid = ref[key] = vals.length
  43.  
  44. conv(val, newid)
  45.  
  46. })
  47. }
  48.  
  49.  
  50. conv(obj, 0)
  51. return JSON.stringify(refs)
  52.  
  53. }
  54.  
  55. }
  56.  
  57.  
  58.  
  59. function test(id, obj) {
  60.  
  61. console.group('test ' + id)
  62. var xjson = XJSON.stringify(obj)
  63. console.log(xjson)
  64. var xobj = XJSON.parse(xjson)
  65. console.dir(xobj)
  66. console.dir(obj)
  67. console.groupEnd('test ' + id)
  68.  
  69. }
  70.  
  71.  
  72.  
  73. function testing() {
  74.  
  75. var obj1 = { o: {} }
  76. obj1.o = obj1
  77.  
  78. var obj2 = {
  79. a: {
  80. b: {
  81. c: 'xyz',
  82. d: {},
  83. e: 123,
  84. f: {},
  85. g: [true, false]
  86. },
  87. h: {}
  88. }
  89. }
  90.  
  91. obj2.a.b.d = obj2
  92. obj2.a.b.f = obj2.a
  93. obj2.a.h = obj2.a.b
  94.  
  95. test(1, obj1)
  96. test(2, obj2)
  97.  
  98. }
  99.  
  100.  
  101. testing()
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty