Using ActiveRecord::Base.to_json I do:
user = User.find_by_name 'Mika'
{"created_at":"2011-07-10T11:30:49+03:00","id":5,"is_deleted":null,"name":"Mika"}
Now, what I would like to have is:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
}
Is there an option to do this?
It would be great to have a global option, so that the behaviour be set depending on dev/live environment.
I’ll go out on a limb and say “no, there is no such option”.
AFAIK, the JSON encoding is actually handled by ActiveSupport rather than ActiveRecord. If you look at
lib/active_support/json/encoding.rbfor your ActiveSupport gem, you’ll see a lot of monkey patching going on to addas_jsonandencode_jsonmethods to some core classes; theas_jsonmethods are just used to flatten things like Time, Regexp, etc. to simpler types such as String. The interesting monkey patches are theencode_jsonones, those methods are doing the real work of producing JSON and there’s nothing in them for controlling the final output format; the Hash version, for example, is just this:The
encoderjust handles things like Unicode and quote escaping. As you can see, theencode_jsonis just mashing it all together in one compact string with no options for enabling prettiness.All the complex classes appear to boil down to Hash or Array during JSONification so you could, in theory, add your own monkey patches to Hash and Array to make them produce something pretty. However, you might have some trouble keeping track of how deep in the structure you are so producing this:
Would be pretty straight forward but this:
would be harder and, presumably, you’d want the latter and especially so with deeply nested JSON where eyeballing the structure is difficult. You might be able to hang a bit of state on the
encoderthat gets passed around but that would be getting a little ugly and brittle.A more feasible option would be an output filter to parse and reformat the JSON before sending it off to the browser. You’d have to borrow or build the pretty printer but that shouldn’t be that difficult. You should be able to conditionally attach said filter only for your development environment without too much ugliness as well.
If you’re just looking to debug your JSON based interactions then maybe the JSONovich extension for Firefox would be less hassle. JSONovich has a few nice features (such as expanding and collapsing nested structures) that go beyond simple pretty printing too.
BTW, I reviewed Rails 3.0 and 3.1 for this, you can check Rails 2 if you’re interested.