2011-01-05 78 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