【问题标题】:Convert nested array to JSON将嵌套数组转换为 JSON
【发布时间】:2013-06-03 08:23:00
【问题描述】:

这段代码:

@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"],
   .
   .
   .
}

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-3


    【解决方案1】:

    这应该可行:

    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。

    【讨论】:

    • 返回,country_name = [...] 但我需要 country_name : [...]
    • 您需要 Ruby 哈希或 JSON 之类的东西吗?
    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2020-02-16
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多