stringify.js 1.0 KB

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