safe-stringify.js 887 B

12345678910111213141516171819202122232425262728293031323334353637
  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(value.map(function (item) { return self(item, replacer, space); })) +
  18. "]"
  19. );
  20. }
  21. return (
  22. "{" +
  23. compact
  24. .call(
  25. toArray(value, function (item, key) {
  26. item = self(item, replacer, space);
  27. if (!item) return null;
  28. return stringify(key) + ":" + item;
  29. })
  30. )
  31. .join(",") +
  32. "}"
  33. );
  34. }
  35. };