stringify.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. var test = require('tape');
  2. var traverse = require('../');
  3. test('stringify', function (t) {
  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. t.equal(s, JSON.stringify(obj));
  32. t.end();
  33. });