仅从Ruby哈希中提取特定成员



我只想从下面从dropbox api返回的哈希中提取team_member_id和display_name。

{"members"=>[{"profile"=>{"team_member_id"=>"dbmid:AACHnGyTHHna44224Ad-vVewFDJ9nzS7be9GJ6Tc", "account_id"=>"dbid:AAD234234234x2yGXHsG3guC04Fp8QPwUF9NDO55w", "email"=>"name@domain.com", "email_verified"=>true, "secondary_emails"=>[], "status"=>{".tag"=>"active"}, "name"=>{"given_name"=>"firstname", "surname"=>"lastname", "familiar_name"=>"first", "display_name"=>"firstname lastname", "abbreviated_name"=>"MM"}, "membership_type"=>{".tag"=>"full"}, "joined_on"=>"2017-01-02T20:58:20Z", "groups"=>["g:6fe6b5a111cfc0400000000000000005", "g:6fe6b5a111cfc04000000000000015a1", "g:6fe6b5a111cfc0400000000000002299", "g:6fe6b5a111cfc04000000000000043cb", "g:6fe6b5a111cfc0400000000000056eb3", "g:6fe6b5a111cfc0400000000000058122", "g:6fe6b5a111cfc0400000000000058248", "g:6fe6b5a111cfc04000000000002dd0d9", "g:6fe6b5a111cfc04000000000002dd650"], "member_folder_id"=>"1384307556"}, "role"=>{".tag"=>"team_admin"}}], "cursor"=>"AAAXuLKhvS_T97ZjALBH4A2MCQW_xOp9bu0tAwqGuY1zBg_C-UKVZoBDTQkhU4Hok8nGT15IHN64ZE-88-dlT3242341WD8RgPBg5zfIOQqAdgJlc-Aw", "has_more"=>true}

我尝试使用下面的代码,结果为零。

puts hash['profile']['team_member_id']

从上面的散列中提取单个数据的推荐方法是什么。

hash["members"]返回一个数组,因此您必须执行以下操作:

hash["members"][0]["profile"]["team_member_id"]
hash["members"][0]["profile"]["name"]["display_name"]

您还可以利用名为dig的方法,该方法同时适用于hasharray。这个的优点是,如果没有找到任何密钥,它会返回nil

hash.dig('members', 0, 'profile', 'team_member_id')
hash.dig('members', 0, 'profile', 'name', 'display_name')

最新更新