如何在JSON结果中分隔键和值

时间:2018-12-26 10:45:17

标签: ruby-on-rails json ruby

当我调用国家/地区列表时,会从API获取以下数组作为JSON:

{
"countries": [
    [
        "Andorra",
        "AD"
    ],
    [
        "United Arab Emirates",
        "AE"
    ],
    [
        "Afghanistan",
        "AF"
    ],
    [
        "Antigua and Barbuda",
        "AG"
    ],
    [
        "Anguilla",
        "AI"
    ],
    [
        "Albania",
        "AL"
    ],
    [
        "Armenia",
        "AM"
]]}

这是我的控制者:

def find_countries
    @countries =  CountryStateSelect.countries_collection
    render :json=>{ :countries=> @countries }
  end

我想这样分隔国家列表数组。

{
    "countries": [
        [
            value:"Andorra",
            key: "AD"
        ],
        [
           value: "United Arab Emirates",
            key:"AE"
        ],
        [
           value: "Afghanistan",
            key:"AF"
        ],
        [
            value:"Antigua and Barbuda",
            key:"AG"
        ]
        ]}

我无法识别值和键。我该如何如上所述分离此JSON响应?

4 个答案:

答案 0 :(得分:5)

您需要将每个项目映射到一个对象

@countries =  CountryStateSelect.countries_collection.map do |name, code|
  Hash[:key, code, :value, name]
end

答案 1 :(得分:1)

只需将您的数组转换为哈希:

h = _ # your input data given

h[:countries].map!{|a| {value: a[0], key: a[1]} }

答案 2 :(得分:1)

input = {
  "countries": [
    ["Andorra", "AD"],
    ["United Arab Emirates", "AE"]        
  ]
} 

input.
  transform_values do |vals|
    vals.map(&%i[value key].method(:zip)).map(&:to_h)
  end

#⇒ {
#   :countries => [
#     [0] {
#         :key => "AD",
#       :value => "Andorra"
#     },
#     [1] {
#         :key => "AE",
#       :value => "United Arab Emirates"
#     }
#   ]
# }

答案 3 :(得分:1)

使用收集方法:

countries = CountryStateSelect.countries_collection.collect do |country, code|
    { key: code, value: country }
end