ruby on rails - ActiveRecord: Produce multi-line human-friendly json -
ruby on rails - ActiveRecord: Produce multi-line human-friendly json -
using activerecord::base.to_json do:
user = user.find_by_name 'mika' {"created_at":"2011-07-10t11:30:49+03:00","id":5,"is_deleted":null,"name":"mika"}
now, have is:
{ "created_at":"2011-07-10t11:30:49+03:00", "id":5, "is_deleted":null, "name":"mika" }
is there alternative this?
it great have global option, behaviour set depending on dev/live environment.
i'll go out on limb , "no, there no such option".
afaik, json encoding handled activesupport rather activerecord. if @ lib/active_support/json/encoding.rb
activesupport gem, you'll see lot of monkey patching going on add together as_json
, encode_json
methods core classes; as_json
methods used flatten things time, regexp, etc. simpler types such string. interesting monkey patches encode_json
ones, methods doing real work of producing json , there's nil in them controlling final output format; hash version, example, this:
# comments removed clarity def encode_json(encoder) "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}" end
the encoder
handles things unicode , quote escaping. can see, encode_json
mashing in 1 compact string no options enabling prettiness.
all complex classes appear boil downwards hash or array during jsonification could, in theory, add together own monkey patches hash , array create them produce pretty. however, might have problem keeping track of how deep in construction producing this:
{ "created_at":"2011-07-10t11:30:49+03:00", "id":5, "is_deleted":null, "name":"mika" "nested":{ "not":"so pretty now", "is":"it" } }
would pretty straight forwards this:
{ "created_at":"2011-07-10t11:30:49+03:00", "id":5, "is_deleted":null, "name":"mika" "nested": { "not":"so pretty now", "is":"it" } }
would harder and, presumably, you'd want latter , nested json eyeballing construction difficult. might able hang bit of state on encoder
gets passed around getting little ugly , brittle.
a more feasible alternative output filter parse , reformat json before sending off browser. you'd have borrow or build pretty printer shouldn't difficult. should able conditionally attach said filter development environment without much ugliness well.
if you're looking debug json based interactions maybe jsonovich extension firefox less hassle. jsonovich has few nice features (such expanding , collapsing nested structures) go beyond simple pretty printing too.
btw, reviewed rails 3.0 , 3.1 this, can check rails 2 if you're interested.
ruby-on-rails ruby json activerecord
Comments
Post a Comment