stringify.js 921 B

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