UNPKG

1.05 kBJavaScriptView Raw
1#!/usr/bin/env node
2var traverse = require('traverse');
3
4var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
5
6var s = '';
7traverse(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
37console.log('JSON.stringify: ' + JSON.stringify(obj));
38console.log('this stringify: ' + s);