2

While JSON.stringify allows you to pass a custom replacer, JSON.parse allows you to pass a custom reviver. This can be really helpful for e.g. RegExp type, because it can't be de-/serialized by default:

var o = {
  foo: "bar",
  re: /foo/gi
};

function replacer(key, value) {
  if (value instanceof RegExp)
    return ("__REGEXP " + value.toString());
  else
    return value;
}

function reviver(key, value) {
  if (value.toString().indexOf("__REGEXP ") == 0) {
    var m = value.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/);
    return new RegExp(m[1], m[2] || "");
  } else
    return value;
}

console.log(JSON.parse(JSON.stringify(o, replacer, 2), reviver));

Question

Is it possible to add such a replacer and reviver globally?

ysfaran
  • 5,189
  • 3
  • 21
  • 51

1 Answers1

1

If i get your question correctly - if you want to make all future JSON.stringifies to use your replacer - you can overwrite the standard function like this:

JSON.stringify_original = JSON.stringify;
JSON.stringify = function(o, r, s){
  r = function(key, value){
    if (value instanceof RegExp)
      return ("__REGEXP " + value.toString());
    else
      return value;
  }
  return JSON.stingify_original(o, r, s);
}

and then do something similar with the parser. If you put that before other scripts run - globally your replacer will be applied.

webdev-dan
  • 1,339
  • 7
  • 10
  • I was also thinking about such an approach, but hoped there would be a built-in solution for this. What I don't like about your current solution is that you can't pass another `replacer` from the calling side because it would always be overriden. But I guess it's not a big deal to add this functionality, thanks! – ysfaran Jan 25 '21 at 09:32