1 | #!/usr/bin/env node
|
2 | var traverse = require('traverse');
|
3 |
|
4 | var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
|
5 |
|
6 | var s = '';
|
7 | traverse(obj).forEach(function to_s (node) {
|
8 | if (Array.isArray(node)) {
|
9 | this.before(function () { s += '[' });
|
10 | this.post(function (child) {
|
11 | if (!child.isLast) s += ',';
|
12 | });
|
13 | this.after(function () { s += ']' });
|
14 | }
|
15 | else if (typeof node == 'object') {
|
16 | this.before(function () { s += '{' });
|
17 | this.pre(function (x, key) {
|
18 | to_s(key);
|
19 | s += ':';
|
20 | });
|
21 | this.post(function (child) {
|
22 | if (!child.isLast) s += ',';
|
23 | });
|
24 | this.after(function () { s += '}' });
|
25 | }
|
26 | else if (typeof node == 'string') {
|
27 | s += '"' + node.toString().replace(/"/g, '\\"') + '"';
|
28 | }
|
29 | else if (typeof node == 'function') {
|
30 | s += 'null';
|
31 | }
|
32 | else {
|
33 | s += node.toString();
|
34 | }
|
35 | });
|
36 |
|
37 | console.log('JSON.stringify: ' + JSON.stringify(obj));
|
38 | console.log('this stringify: ' + s);
|