SkRoR
SkRoR

Reputation: 1199

How to separate keys and values in JSON result

I get the following array as JSON from an API when I call a country list:

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

This is my controller:

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

I want to separate this country list array like this.

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

I cannot identify the value and the key. How can I separate this JSON response as above?

Upvotes: 0

Views: 498

Answers (4)

Ursus
Ursus

Reputation: 30056

You need to map each item into an object

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

Upvotes: 5

Ni3
Ni3

Reputation: 286

Using collect method:

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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"
#     }
#   ]
# }

Upvotes: 1

lacostenycoder
lacostenycoder

Reputation: 11226

Just convert your arrays to hashes:

h = _ # your input data given

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

Upvotes: 1

Related Questions