New in Edge Rails: Serialize ActiveRecord objects to JSON with ActiveRecord#to_json

In: JavaScript|Ruby on Rails

24 Sep 2007

Converting ActiveRecord instances to their JSON representation has always been a topic that has been dear to me. I’d tried to get a patch that adds to_json to ActiveRecord into Rails (but the quality of my patch was lacking in a few respects). The Jsonifier plugin that I wrote tried to address the lack of built-in JSON serialization by adding a ActiveRecord#to_json method that acts much like ActiveRecord#to_xml.

So it is with mixed feelings when I discovered a couple of days ago when DHH committed a changeset that added a native ActiveRecord#to_json method. Of course, I’m elated that JSON serialization is given first class attention now, since the raison d’être of Jsonifier and my Rails patch was to do just that. A little bit of me is selfishly disappointed since it means that Jsonifier has become quite obsolete!

But it is an excellent change, I look forward to patching it up (if DHH doesn’t beat me to it – there’ve been so much activity on the Rails trunk recently) so that the JSON serializer supports an :include options for including associations much like for ActiveRecord#to_xml and Jsonifier’s mixed in to_json.

Update: I’ve submitted a patch for adding :include to ActiveRecord#to_json. Please test it and give feedback or +1 ;).

2 Responses to New in Edge Rails: Serialize ActiveRecord objects to JSON with ActiveRecord#to_json

Avatar

DHH

September 24th, 2007 at 10pm

Please do patch away. It would be great to have feature parity between to_xml and to_json before 2.0 final is released.

Avatar

Chu Yeow

September 26th, 2007 at 12am

Patch submitted: http://dev.rubyonrails.org/ticket/9677

I’ll try and get some +1 and feedback.