开发者

Rails: How to extract values from JSON

开发者 https://www.devze.com 2023-02-02 22:38 出处:网络
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\",

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 a开发者_运维技巧nd 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!


without any other gems:

ActiveSupport::JSON.decode(your_json)


# 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号