Ruby-on-rails – Convert nested array to JSON


This code: { |l| [l.country_name, l.latitude, l.longitude,] }


[["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[ { |l| [l.country_name, [l.latitude, l.longitude,]] }]

Rails also provides index_by:

# => {
#      "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:

You can also call to_json manually:

hash = Hash[ { |l| [l.country_name, [l.latitude, l.longitude,]] }]

Or use the JSON Builder gem.