File: test.js

package info (click to toggle)
node-json-stringify-safe 5.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 76 kB
  • ctags: 23
  • sloc: makefile: 2
file content (128 lines) | stat: -rw-r--r-- 2,275 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
var stringify = require('./stringify.js');

var circularObj = { a: 'b' };
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];

//////////
// default
var testObj = {
  "a": "b",
  "circularRef": "[Circular ~]",
  "list": [
    "[Circular ~]",
    "[Circular ~]"
  ]
};

var assert = require('assert');
assert.equal(JSON.stringify(testObj, null, 2),
             stringify(circularObj, null, 2));

assert.equal(JSON.stringify(testObj, null, 2),
            JSON.stringify(circularObj, stringify.getSerialize(), 2));


////////
// prune
testObj = {
  "a": "b",
  "list": [
    null,
    null
  ]
};

function prune(k, v) {}

assert.equal(JSON.stringify(testObj, null, 2),
             stringify(circularObj, null, 2, prune));

///////////
// re-cycle
// (throws)
function recycle(k, v) {
  return v;
}

assert.throws(function() {
  stringify(circularObj, null, 2, recycle);
});

////////
// fancy
testObj = {
  "a": "b",
  "circularRef": "circularRef{a:string,circularRef:Object,list:Array}",
  "list": [
    "0{a:string,circularRef:Object,list:Array}",
    "1{a:string,circularRef:Object,list:Array}"
  ]
};

function signer(key, value) {
  var ret = key + '{';
  var f = false;
  for (var i in value) {
    if (f)
      ret += ',';
    f = true;
    ret += i + ':';
    var v = value[i];
    switch (typeof v) {
      case 'object':
        if (!v)
          ret += 'null';
        else if (Array.isArray(v))
          ret += 'Array'
        else
          ret += v.constructor && v.constructor.name || 'Object';
        break;
      default:
        ret += typeof v;
        break;
    }
  }
  ret += '}';
  return ret;
}

assert.equal(JSON.stringify(testObj, null, 2),
             stringify(circularObj, null, 2, signer));


///////
//multi
var a = { x: 1 };
a.a = a;
var b = { x: 2 };
b.a = a;

var c = { a: a, b: b };
var d = { list: [ a, b, c ] };
d.d = d;

var multi = {
  "list": [
    {
      "x": 1,
      "a": "[Circular ~.list.0]"
    },
    {
      "x": 2,
      "a": "[Circular ~.list.0]"
    },
    {
      "a": "[Circular ~.list.0]",
      "b": "[Circular ~.list.1]"
    }
  ],
  "d": "[Circular ~]"
};

assert.equal(JSON.stringify(multi, null, 2),
             stringify(d, null, 2));

////////
// pass!
console.log('ok');