Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JavaScript objects not have a toJSON() method?

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.

like image 690
Jeff Hammerbacher Avatar asked Jan 03 '10 23:01

Jeff Hammerbacher


2 Answers

The Real Reason

While @CMS is correct, the Browser makes have added these, the point was missed entirely. The reason is that the JSON Specification calls for an optional toJSON method for any object which, in turn, gets called to serialize a non-normative structure into a normative one.

var O = function O() {
    this.val = 'value';
    this.toJSON = function () { return ['VALUE!']; };
};

var o = new O();
var s = JSON.stringify(o);

console.log(s);  // >> ["VALUE!"]

An example would be a Set Data-Structure whose structure is actually an object which has a values method. This would allow one to write this.toJSON = values; to provide the JSON.stringify method the right serialization-strategy.

So, in a nutshell, its to provide JSON.stringify the correct strategy for outputting alternative structures.

Hope this helps.

like image 167
Cody Avatar answered Oct 01 '22 01:10

Cody


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...

like image 25
Christian C. Salvadó Avatar answered Oct 01 '22 01:10

Christian C. Salvadó