如何访问JSON数组数据? [英] How do I access JSON array data?
本文介绍了如何访问JSON数组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组:
[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}
]
如何获取两个ID以便进一步处理作为输出?
How can I get both ids for futher processing as output?
我尝试了很多,但没有成功.我的问题是,我总是只获得一个id作为输出:
I tried a lot but no success. My problem is I always get only one id as output:
Market.all.select.each do |market|
present market.id
end
或者:
Market.all.each{|attributes| present attributes[:id]}
当我需要两个ID时,结果只给我"eurgbp".
which gives me only "eurgbp" as a result while I need both ids.
推荐答案
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
将jSON响应转换为Hash
,然后仅使用标准的Hash
方法进行访问.
JSON#parse
turns a jSON response into a Hash
then just use standard Hash
methods for access.
这篇关于如何访问JSON数组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文