How to return 2 json objects at once?

json, rest, ruby-on-rails, ruby-on-rails-3

Solution

Sounds like you should be constructing something upon which `to_json` can easily be called.

The obvious candidate for active record objects is `as_json`. This does everything that `to_json` does (include the `:include` option and so on) except actually turning the object into json. Instead you get back a ruby hash which you can manipulate as you want and then call to_json. For example you could do

render :json => {
  :o1 => object1.as_json(:include => :blah),
  :o2 => object2.as_json(:include => :blah)
}

Problem

I have a controller returning a json structure like so: ``` def show # ....... o_json = deep_object_1_to_json(o) render :json => o_json end private def deep_object_1_to_json(o) o.to_json( :include => {....}) end ``` Now I need to extend it to return 2 objects. However the obvious solution is giving me problems: ``` def show # ....... o1_json = deep_object_1_to_json(o) o2_json = deep_object_2_to_json(o) render :json => { :object_1 => o1_json, :object_2 => o2_json } end ``` This returns a json object with 2 strings of escaped json data! The deep_object_2_to_json functions already have several layers of nested includes so I would rather not have to refactor these into a single function. Is there a way to make this easily extendable to add more objects in the future without the double escaping problem above? Thanks for any pointers.

Original source