这段代码:
@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 latitude:..., longitude:...>,
# "country_name_2" => #<Country latitude:..., longitude:...>,
# }
对象可能比散列更方便。
关于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 。
关于ruby-on-rails - 将嵌套数组转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892602/