-
Notifications
You must be signed in to change notification settings - Fork 44
Overriding to_json in a class causes associated objects to over-quote and over-escape #16
Comments
I did notice def to_json(*args) super is returning a hash, but that isn’t valid JSON. What is the correct way to do this now? by mpd |
@namelessjon: assigning this to you because (I think?) you recently did some work on to_json in dm-serializer. by Dan Kubb (dkubb) |
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 by Jonathan Stott (namelessjon) |
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. by mpd |
You can work around it by calling to_a on the collection before to_json. So in the above example, @bar.foos.to_a.to_json should work fine. by Dane Jensen |
Any progress on this issue? by Dan Kubb (dkubb) |
As I see it, there are basically two options:
Also, the @to_json@ method in the example could check to see if @Args@ is a hash, and if it has the @:to_json@ option set to false, and if so, just return a hash. by Jonathan Stott (namelessjon) |
Any progress on this issue? |
No. Not really. Happy to accept pull requests though :) |
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.
Created by mpd - 2009-10-03 19:06:22 UTC
Original Lighthouse ticket: http://datamapper.lighthouseapp.com/projects/20609/tickets/1075
The text was updated successfully, but these errors were encountered: