Overriding to_json in a class causes associated objects to over-quote and over-escape
Reported by mpd | October 3rd, 2009 @ 02:06 PM
Any suggestions for a clearer title for this ticket would be very much appreciated ;)
If you override to_json in a class Foo, and class Bar has n foos, calling @bar.foos.to_json in an instance of Bar will emit bad JSON which has too many quotes and backslash escapes.
I created a toy project that demonstrates this at http://github.com/xxx/dm10-association_to_json .
Maybe there's just a different way to do this now.
Comments and changes to this ticket
- State changed from unconfirmed to accepted
Okay, I know why this is happening. It's due to the changes I made to speed things up, which has the side effect of slightly breaking the assumptions the JSON library is making. I will try and work out how to safely allow overriding while keeping the speedup for users who arn't doing this.
As a temporary measure, what are you trying to accomplish with the custom method? It may be possible to duplicate that through options to the
I'm aggregating a bunch of method return values from an associated object (and those methods are not known until runtime, so the associated object is queried both for the methods to include and the results.)
I could get around it by delegating methods or using method_missing. I'm not terribly keen on doing either for this sort of operation, though.
As I see it, there are basically two options:
- Revert the original patch and go back to manually constructing
- Do as AMo do, and have a
as_hash(or method with that intent, at least) and a
to_json. It would then be possible to override
as_hashhowever you liked, and
to_jsonwould just call
to_jsonmethod in the example could check to see if
argsis a hash, and if it has the
:to_jsonoption set to false, and if so, just return a hash.
- Revert the original patch and go back to manually constructing JSON.