Ruby-on-rails – Convert nested array to JSON

jsonrubyruby-on-railsruby-on-rails-3

This code:

@countries.map { |l| [l.country_name, l.latitude, l.longitude, l.capital] }

returns

[["country_name_1", latitude, longitude, capital],["country_name_2", latitude, longitude, capital],...]

But I need to convert to JSON; something like this:

{
   "country_name_1" : [latitude, longitude, "capital"],
   "country_name_2" : [latitude, longitude, "capital"],
   .
   .
   .
}

Best Solution

This should work:

Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }]

Rails also provides index_by:

@countries.index_by(&:country_name)
# => {
#      "country_name_1" => #<Country latitude:..., longitude:...>,
#      "country_name_2" => #<Country latitude:..., longitude:...>,
#    }

Objects might be more convenient than hashes.

Regarding JSON

Rails has built-in support for JSON: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json

You can also call to_json manually:

hash = Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }]
hash.to_json

Or use the JSON Builder gem.