Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  111] [ 6]  / answers: 1 / hits: 20057  / 12 Years ago, wed, august 22, 2012, 12:00:00

So, I was interested to find that JSON.stringify reduces a RegExp to an empty object-literal (fiddle):



JSON.stringify(/^[0-9]+$/) // {}


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


I would have hoped that JSON would give RegExp the same consideration by using RegExp.prototype.toString().


More From » json

 Answers
42

Yes, because there's no canonical representation for a RegExp object in JSON. Thus, it's just an empty object.



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.


[#83479] Tuesday, August 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiemarvinm

Total Points: 473
Total Questions: 103
Total Answers: 94

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;