safe-stringify.js 910 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. "use strict";
  2. var compact = require("../array/#/compact")
  3. , isObject = require("../object/is-object")
  4. , toArray = require("../object/to-array")
  5. , isArray = Array.isArray
  6. , stringify = JSON.stringify;
  7. module.exports = function self(value /*, replacer, space*/) {
  8. var replacer = arguments[1], space = arguments[2];
  9. try {
  10. return stringify(value, replacer, space);
  11. } catch (e) {
  12. if (!isObject(value)) return null;
  13. if (typeof value.toJSON === "function") return null;
  14. if (isArray(value)) {
  15. return (
  16. "[" +
  17. compact.call(
  18. value.map(function (item) {
  19. return self(item, replacer, space);
  20. })
  21. ) +
  22. "]"
  23. );
  24. }
  25. return (
  26. "{" +
  27. compact
  28. .call(
  29. toArray(value, function (item, key) {
  30. item = self(item, replacer, space);
  31. if (!item) return null;
  32. return stringify(key) + ":" + item;
  33. })
  34. )
  35. .join(",") +
  36. "}"
  37. );
  38. }
  39. };