Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to extract values from JSON

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!

like image 690
ismcc Avatar asked Jan 05 '11 21:01

ismcc


2 Answers

without any other gems:

ActiveSupport::JSON.decode(your_json)

like image 109
Omar Qureshi Avatar answered Nov 03 '22 01:11

Omar Qureshi


# 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
like image 23
yfeldblum Avatar answered Nov 02 '22 23:11

yfeldblum