Rails:如何从JSON中提取值

5

非常简单的问题(我是新手)。我从 Facebook 获取了一个 JSON 响应,其中包含名称和 ID:

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

我该如何在保留数据结构的同时,在我的rails应用程序中提取和访问这些数据?我想要告诉rails - “给我第二个条目的id”,或者“给我第275个条目” - 这些内容。请假设回答者没有任何知识。谢谢!
2个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接