Harmonizing JSON/XML serialization

The way Rails handles root nodes in JSON and XML serialization is inconsistent. This has been discussed before:

https://rails.lighthouseapp.com/projects/8994/tickets/2584-232-activeresource-json-doesnt-send-parameters-with-root-node

This seems mostly taken care of with ActiveModel::Base.include_root_in_json, especially if/when it ends up in ActiveResource. However, there is also the issue of how Enumerables are serialized. This ticket would have me believe that it's a solved issue in Rails 3:

https://rails.lighthouseapp.com/projects/8994/tickets/3812-collection-root-for-enumerable-to_json

But how is this being taken care of exactly? It seems like, for consistency's sake, we'd want the structure of JSON serialization to be as close to Hash#from_xml's output as possible. This is the state of affairs with 3.0.0.beta2 (the last two expressions are the most important for this discussion):

Loading development environment (Rails 3.0.0.beta2) irb(main):001:0> foo = Thing.first => #<Thing id: 1, name: "foo"> irb(main):002:0> Thing.include_root_in_json = true => true irb(main):003:0> puts foo.to_json {"thing":{"name":"foo","id":1}} => nil irb(main):004:0> Hash.from_xml(foo.to_xml) => {"thing"=>{"name"=>"foo", "id"=>1}} irb(main):005:0> puts [foo].to_json [{"thing":{"name":"foo","id":1}}] => nil irb(main):006:0> Hash.from_xml([foo].to_xml) => {"things"=>[{"name"=>"foo", "id"=>1}]}

I think we should make the default JSON serialization output [foo].to_json like this:

{"things": [{"name":"foo","id":1}]}

...in order to be consistent with XML. Thoughts?

-James

But how is this being taken care of exactly? It seems like, for consistency's sake, we'd want the structure of JSON serialization to be as close to Hash#from_xml's output as possible.

I'm actually not sure I agree with the desire for consistency here. Working (in javascript) with a to_json'd AR object is actually annoying now.

You get an array of 'customers', but then in order to get the customer's first_name you need to do:

customers.each(function(customer) {   alert(customer.customer.first_name); });

I'm not sure that it'd be an improvement to move this to:

customers.customers.each(function(customer) {   alert(customer.customer.first_name); });

JSON is not XML. What you are proposing is to use JSON as though it were XML, which doesn't make any sense in my oppinion. Let them each play to their strengths.

/Jonas