Rails: How to extract values from JSON

2020-07-17 06:40发布

问题:

Very simple question (I am beginner). I have a JSON response from fb containing names and ids:

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

How do I extract and access this data in my rails app while preserving its structure? I'd like to be able to tell rails - "give me the id of the 2nd entry", or, "give me the 275th entry" - these sorts of things.

Please assume no knowledge when answering. thx!

回答1:

without any other gems:

ActiveSupport::JSON.decode(your_json)



回答2:

# 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