stringify.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var assert = require('assert');
  2. var Traverse = require('traverse');
  3. exports.stringify = function () {
  4. var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
  5. var s = '';
  6. Traverse(obj).forEach(function (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. }
  14. else if (typeof node == 'object') {
  15. this.before(function () { s += '{' });
  16. this.pre(function (x, key) {
  17. s += '"' + key + '"' + ':';
  18. });
  19. this.post(function (child) {
  20. if (!child.isLast) s += ',';
  21. });
  22. this.after(function () { s += '}' });
  23. }
  24. else if (typeof node == 'function') {
  25. s += 'null';
  26. }
  27. else {
  28. s += node.toString();
  29. }
  30. });
  31. assert.equal(s, JSON.stringify(obj));
  32. }