将嵌套数组转换为JSON
这段代码:
@countries.map { |l| [l.country_name, l.latitude, l.longitude, l.capital] }
回报
[["country_name_1", latitude, longitude, capital],["country_name_2", latitude, longitude, capital],...]
但我需要转换为JSON; 像这样的东西:
{ "country_name_1" : [latitude, longitude, "capital"], "country_name_2" : [latitude, longitude, "capital"], . . . }
这应该工作:
Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }]
Rails还提供index_by
:
@countries.index_by(&:country_name) # => { # "country_name_1" => #, # "country_name_2" => # , # }
对象可能比哈希更方便。
关于JSON
Rails内置了对JSON的支持: http : //guides.rubyonrails.org/layouts_and_rendering.html#rendering-json
您也可以手动调用to_json
:
hash = Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }] hash.to_json
或者使用JSON Builder gem。