如何访问JSON数组数据?
我有以下数组:
[ { "attributes": { "id": "usdeur", "code": 4 }, "name": "USD/EUR" }, { "attributes": { "id": "eurgbp", "code": 5 }, "name": "EUR/GBP" } ]
如何将两个ID作为输出进行进一步处理?
我尝试了很多但没有成功。 我的问题是我总是只得到一个id作为输出:
Market.all.select.each do |market| present market.id end
要么:
Market.all.each{|attributes| present attributes[:id]}
这让我只有“eurgbp”,因为我需要两个ID。
JSON#parse
应该可以帮助你解决这个问题
require 'json' json = '[ { "attributes": { "id": "usdeur", "code": 4 }, "name": "USD/EUR" }, { "attributes": { "id": "eurgbp", "code": 5 }, "name": "EUR/GBP" }]' ids = JSON.parse(json).map{|hash| hash['attributes']['id'] } #=> ["usdeur", "eurgbp"]
JSON#parse
#parse将jSON响应转换为Hash
然后只使用标准Hash
方法进行访问。
我将假设数据是JSON,你正在解析(使用JSON.parse
)到Ruby的Hashes数组中,它看起来像这样:
hashes = [ { "attributes" => { "id" => "usdeur", "code" => 4 }, "name" => "USD/EUR" }, { "attributes" => { "id" => "eurgbp", "code" => 5 }, "name" => "EUR/GBP" } ]
如果你想获得第一个"id"
值,你可以这样做:
first_hash = hashes[0] first_hash_attributes = first_hash["attributes"] p first_hash_attributes["id"] # => "usdeur"
要不就:
p hashes[0]["attributes"]["id"] # => "usdeur"
为了得到它们,你会这样做:
all_attributes = hashes.map {|hash| hash["attributes"] } # => [ { "id" => "usdeur", "code" => 4 }, # { "id" => "eurgbp", "code" => 5 } ] all_ids = all_attributes.map {|attrs| attrs["id"] } # => [ "usdeur", "eurgbp" ]
要不就:
p hashes.map {|hash| hash["attributes"]["id"] } # => [ "usdeur", "eurgbp" ]
使用Rails的JSON库很慢……
我更喜欢使用:
gem 'oj'
来自https://github.com/ohler55/oj
快速而简单! 我们走吧!