问题描述
所以,我有兴趣发现 JSON.stringify
将一个RegExp简化为一个空的object-literal():
So, I was interested to find that JSON.stringify
reduces a RegExp to an empty object-literal (fiddle):
JSON.stringify(/^[0-9]+$/) // "{}"
预计会出现这种情况吗?我意识到RegExp是一个没有要序列化属性的对象。也就是说,日期也是对象;但是 JSON.stringify()
设法生成一个有意义的字符串:
Is this behavior expected? I realize that a RegExp is an object with no properties to serialize. That said, dates are objects too; yet JSON.stringify()
manages to produce a meaningful string:
JSON.stringify(new Date) // "2014-07-03T13:42:47.905Z"
我希望JSON通过使用 RegExp.prototype给RegExp同样的考虑。
。
I would have hoped that JSON would give RegExp the same consideration by using RegExp.prototype.toString()
.
推荐答案
是的,因为在JSON中没有RegExp对象的规范表示。因此,它只是一个空物体。
Yes, because there's no canonical representation for a RegExp object in JSON. Thus, it's just an empty object.
编辑 - 现在是2018年;使用 .toJSON()
等建议解决方案的答案可能还不错,不过我会将方法添加到原型中
edit — well it's 2018 now; the answers suggesting solutions using .toJSON()
etc are probably fine, though I'd add the method to the prototype with
Object.defineProperty(RegExp.prototype, "toJSON", {
value: RegExp.prototype.toString
});
依此类推。这确保了函数名称不可枚举,这使得猴子补丁更加卫生。
and so on. That ensures that the function name isn't enumerable, which makes the monkey-patch somewhat more hygienic.
这篇关于RegExp的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!