name: {
"accounts"=>{
"data"=>[
{
"access_token"=>"CAAUCR7n0ZC50BAGmqTb3FEYz9FzZCZAZBFdVZC6AM3iQrGUsVqWvCfI5q5vh4seRH6LwIQTSkZAznzeBaPlZBjQ3zcwdfWxPBIr78FZBVa8pymUzVX0UESSS7QC0Dm7iIUCMyRH175HV6ZCa2ugBmbJNB7joZB7oiILPH5jtpcCLkg8e7ztxyjeSODSO4ZBAM9z1pkZD",
"name"=>"UNX",
"id"=>"387832931391777",
},
{
"access_token"=>"CAAUCR7n0ZC50BAEYnXR7bWGvhktsGXCaB43vB0mhSuKgZBQG1m5FyovssyVKt0XYv7K7essxPkVPU3nQZCqrQJeTtWhApV1cSYGsb4JbNmYlUiHmLHueEBjuomqRWVX6tvMZA0dA5zqMApbmPUtA7SBqruWUFzZAwZC9xZBXFMZCZAW7WNEL7epkb9dmiL2pX3AoZD",
"name"=>"Fuitter",
"id"=>"1412081982453898",
}
]}}
我正在尝试从name
哈希数组中获取data
键。我已经使用each
循环,但这样我必须在循环内嵌套循环。有没有其他方法可以使这项工作?
这个name
键实际上是数据类型为json的数据库中的列。
<% session[:user].account.name.each do |test| %>
<% test.each do |me| %>
<%= me['data']['name']%> #unable to fetch name and gives me undefined method `[]' for nil:NilClass error
<br>
<% end %>
<% end %>
我试图通过嵌套循环来获取值,但是我收到了这个错误
unable to fetch name and gives me undefined method `[]' for nil:NilClass error
答案 0 :(得分:0)
这样做:
data_hash = { name: {
"accounts"=>{
"data"=>[
{
"access_token"=>"CAAUCR7n0ZC50BAGmqTb3FEYz9FzZCZAZBFdVZC6AM3iQrGUsVqWvCfI5q5vh4seRH6LwIQTSkZAznzeBaPlZBjQ3zcwdfWxPBIr78FZBVa8pymUzVX0UESSS7QC0Dm7iIUCMyRH175HV6ZCa2ugBmbJNB7joZB7oiILPH5jtpcCLkg8e7ztxyjeSODSO4ZBAM9z1pkZD",
"name"=>"UNX",
"id"=>"387832931391777",
},
{
"access_token"=>"CAAUCR7n0ZC50BAEYnXR7bWGvhktsGXCaB43vB0mhSuKgZBQG1m5FyovssyVKt0XYv7K7essxPkVPU3nQZCqrQJeTtWhApV1cSYGsb4JbNmYlUiHmLHueEBjuomqRWVX6tvMZA0dA5zqMApbmPUtA7SBqruWUFzZAwZC9xZBXFMZCZAW7WNEL7epkb9dmiL2pX3AoZD",
"name"=>"Fuitter",
"id"=>"1412081982453898",
}
]
}
}
}
data_hash[:name]['accounts']['data'].map { |d| puts d['name'] }
# => UNX
# => Fuitter