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?