Sre*_*RoR 0 ruby json ruby-on-rails
当我调用国家/地区列表时,我从API获取以下数组作为JSON:
{
"countries": [
[
"Andorra",
"AD"
],
[
"United Arab Emirates",
"AE"
],
[
"Afghanistan",
"AF"
],
[
"Antigua and Barbuda",
"AG"
],
[
"Anguilla",
"AI"
],
[
"Albania",
"AL"
],
[
"Armenia",
"AM"
]]}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
def find_countries
@countries = CountryStateSelect.countries_collection
render :json=>{ :countries=> @countries }
end
Run Code Online (Sandbox Code Playgroud)
我想像这样分开这个国家/地区列表数组.
{
"countries": [
[
value:"Andorra",
key: "AD"
],
[
value: "United Arab Emirates",
key:"AE"
],
[
value: "Afghanistan",
key:"AF"
],
[
value:"Antigua and Barbuda",
key:"AG"
]
]}
Run Code Online (Sandbox Code Playgroud)
我无法确定价值和关键.如何将上述JSON响应分开?
您需要将每个项目映射到一个对象
@countries = CountryStateSelect.countries_collection.map do |name, code|
Hash[:key, code, :value, name]
end
Run Code Online (Sandbox Code Playgroud)