jsons.js 780 B

123456789101112131415161718192021222324252627282930
  1. Jsons = {
  2. stringify(value) {
  3. const ret = JSON.stringify(value, this.replacer, 2);
  4. return ret;
  5. },
  6. parse(value) {
  7. const ret = JSON.parse(value, this.reviver);
  8. return ret;
  9. },
  10. // https://stackoverflow.com/questions/12075927/serialization-of-regexp/33416684#33416684
  11. replacer(key, value) {
  12. if (value instanceof RegExp)
  13. return ("___REGEXP___ " + value.toString());
  14. else
  15. return value;
  16. },
  17. // https://stackoverflow.com/questions/12075927/serialization-of-regexp/33416684#33416684
  18. reviver(key, value) {
  19. if (value?.toString()?.indexOf("___REGEXP___ ") == 0) {
  20. const m = value.split("___REGEXP___ ")[1].match(/\/(.*)\/(.*)?/);
  21. return new RegExp(m[1], m[2] || "");
  22. } else
  23. return value;
  24. }
  25. }
  26. export { Jsons }