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

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 Comments & TrackBacks (Add yours)

The paper doll icon that precedes each comment is an idea conceived by Vanessa Tan.

Paper doll icon
DHH's Gravatar

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

Posted by: DHH on September 24, 2007 10pm

Paper doll icon
Chu Yeow's Gravatar

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

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

Posted by: Chu Yeow on September 26, 2007 12am

You can subscribe to the RSS feed for comments on this post.

Post a comment

(required)

(required, but never displayed)


You can format your comments using XHTML. Your email address will not be displayed or used for nefarious purposes.

Only following tags are allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>