将嵌套数组转换为JSON [英] Convert nested array to JSON

查看:132
本文介绍了将嵌套数组转换为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;像这样的东西:

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

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

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.

Rails内置了对JSON的支持: http://guides.rubyonrails. org/layouts_and_rendering.html#rendering-json

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

您还可以手动调用 to_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

或使用 JSON Builder gem.

这篇关于将嵌套数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆