As described at http://www.json.org/js.html, JavaScript objects can dictate how they are serialized by JSON.stringify() by implementing a toJSON() method. For an arbitrary object, this method is not defined, while numbers and strings seem to implement the method. I’m curious–why do objects not have an implementation?
EDIT: I originally mentioned that arrays have this method–they do not. I apologize for the confusion.
Those methods you mention were added by some JavaScript engines (AFAIK the latest versions of V8 and Tracemonkey implement them):
Although the only standarized by the ECMAScript 5 Specification is the
Date.prototype.toJSON.Personally I think those methods aren’t much useful at all, the results from
String,Boolean, andNumberare completely equivalent to calling thevalueOfmethod, and the result from Date is equivalent to callingtoISOString.So the question was: Why native objects not have a toJSON() method?
Well, with the
JSONObject available (Section 15.12), adding another method to theObject.prototypeis not worth, and really I think it would be a bad idea adding it…