index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. module.exports = function (data, opts) {
  3. if (!opts) opts = {};
  4. if (typeof opts === 'function') opts = { cmp: opts };
  5. var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
  6. var cmp = opts.cmp && (function (f) {
  7. return function (node) {
  8. return function (a, b) {
  9. var aobj = { key: a, value: node[a] };
  10. var bobj = { key: b, value: node[b] };
  11. return f(aobj, bobj);
  12. };
  13. };
  14. })(opts.cmp);
  15. var seen = [];
  16. return (function stringify (node) {
  17. if (node && node.toJSON && typeof node.toJSON === 'function') {
  18. node = node.toJSON();
  19. }
  20. if (node === undefined) return;
  21. if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
  22. if (typeof node !== 'object') return JSON.stringify(node);
  23. var i, out;
  24. if (Array.isArray(node)) {
  25. out = '[';
  26. for (i = 0; i < node.length; i++) {
  27. if (i) out += ',';
  28. out += stringify(node[i]) || 'null';
  29. }
  30. return out + ']';
  31. }
  32. if (node === null) return 'null';
  33. if (seen.indexOf(node) !== -1) {
  34. if (cycles) return JSON.stringify('__cycle__');
  35. throw new TypeError('Converting circular structure to JSON');
  36. }
  37. var seenIndex = seen.push(node) - 1;
  38. var keys = Object.keys(node).sort(cmp && cmp(node));
  39. out = '';
  40. for (i = 0; i < keys.length; i++) {
  41. var key = keys[i];
  42. var value = stringify(node[key]);
  43. if (!value) continue;
  44. if (out) out += ',';
  45. out += JSON.stringify(key) + ':' + value;
  46. }
  47. seen.splice(seenIndex, 1);
  48. return '{' + out + '}';
  49. })(data);
  50. };