views:

325

answers:

5

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.

+3  A: 

I don't think its the case that Numbers, etc have default toJSON implementations. Maybe you are using Prototype or some other framework?

http://www.w3schools.com/jsref/jsref_obj_number.asp

http://www.w3schools.com/jsref/jsref_obj_array.asp

From http://www.prototypejs.org/learn/json :

Encoding

Prototype’s JSON encoding slightly differs from Crockford’s implementation as it does not extend Object.prototype. The following methods are available: Number#toJSON, String#toJSON, Array#toJSON, Hash#toJSON, Date#toJSON and Object.toJSON.

danben
Nothing has a default toJSON implemention in the ECMAScript spec. http://www.json.org/json2.js gives default implementations for the types Jeff lists, but these just delegate to `valueOf()`.
Michael Greene
A: 

I doubt this is a reason - arrays don't seem to have them either. Here's how I'd implement it:

Array.prototype.toJSON = Object.prototype.toJSON = function() {
  return JSON.stringify(this);
}
dmitrig01
Wouldn't this cause infinite recursion somewhere as JSON.stringify calls `toJSON(key)`?
Michael Greene
A: 

It's a standard to not implement functions on arbitrary objects.

try console.log({}) and you'll see nothing.

Luca Matteis
A: 

What properties would it save? A plain old object doesn't have any.

Noon Silk
+1  A: 

Those methods you mention were added by some JavaScript engines (AFAIK the latest versions of V8 and Tracemonkey implement them):

String.prototype.toJSON
Boolean.prototype.toJSON
Number.prototype.toJSON
Date.prototype.toJSON

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, and Number are completely equivalent to calling the valueOf method, and the result from Date is equivalent to calling toISOString.

So the question was: Why native objects not have a toJSON() method?

Well, with the JSON Object available (Section 15.12), adding another method to the Object.prototype is not worth, and really I think it would be a bad idea adding it...

CMS