2011-01-05 80 views
5

非常簡單的問題(我是初學者)。我有包含名稱和ID FB的JSON響應:Rails:如何從JSON中提取值

[{"name"=>"John Kline", "id"=>"10276192"}, {"name"=>"Quinn Kumbers", 
"id"=>"18093781"}, {"name"=>"Dan Jacobs", "id"=>"100000918716828"}] ... 

我如何提取並同時保持其結構在我的Rails應用程序訪問這些數據?我希望能夠告訴鐵路 - 「給我第二條目的身份證」,或者「給我第275條條目」 - 這些事情。

回答時請不要假設。謝謝!

回答

8

沒有任何其它寶石:

ActiveSupport::JSON.decode(your_json)

6
# HT Omar Qureshi 
data = ActiveSupport::JSON.decode(your_json) 

# with the id of the 2nd entry 
do_something_with(data[1]['id']) 

# with the 275th entry 
do_something_else_with(data[274]) 

# loop over all the results 
data.each do |datum| 
    puts "#{datum['id']}: #{datum['name']}" 
end