The .toJSON method is semantically incorrect for strings and custom types #14

asokoloski opened this Issue Jul 14, 2011 · 2 comments


None yet
1 participant

I understand that this is how json.js is designed, to allow users to easily define their own .toJSON methods and not worry about quoting the return value. In this case, I'm trying to use Orbited, which uses, alongside Prototype, which has its own implementation that also adds .toJSON methods to global types. I think that in json.js is slightly more broken, though, because the name of the method toJSON implies that the return value will always be the actual JSON representation of the object, when in the case of strings the return value is not quoted. It really comes down to semantics more than anything.

What I am about to suggest is unfortunately a backward-incompatible change for users who have taken advantage of the custom .toJSON feature. Would it be feasible to change the semantics of .toJSON to always expect the final JSON representation of the object? To make this more palatable, JSON.quote could be exposed, to allow users to wrap any strings their .toJSON methods return. Or, it could just be specified that you need to call JSON.serialize on whatever you are returning unless you do the serialisation yourself. Although this does require changing application code, it should be quite a minimal and straightforward change.

Or perhaps, the name could be changed to .toPreJSON(), which better reflects the meaning of the method.

I should mention that I'm willing to do the work to make this change, including updating the documentation. But first I just wanted to check and see if you like the idea, and if so which change is preferred.


@asokoloski asokoloski closed this Jul 14, 2011

Never mind, I just realised that prototype 1.7 uses the built-in browser JSON (or json.js's JSON) if it's available. Hurrah!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment