【发布时间】:2011-09-23 09:08:26
【问题描述】:
我正在尝试解析从 facebook 返回的 json。 现在我的想法是从 facebook json 中获取尽可能多的细节。 所以我用like(假设auth是从facebook解析json)
education_array = auth['extra']['user_hash']['education']
education_array.each do |edu|
puts edu['school']['name']
puts edu['type']
puts edu['year']['name']
end
现在的问题是,有些人可能添加了学校名称,但没有添加年份。 很明显
教育['年份']['姓名'] 将抛出错误,告诉“在评估 nil.[] 时发生错误”。
如何避免这种情况?
我认为的一种方式是 puts edu['year']['name']||""
但是如果 'year' 本身不存在,这仍然会引发错误。 (如果没有找到'name'会避免错误)
我不想要以下解决方案: 检查 auth['extra'] 是否存在 然后检查 auth['extra']['user_hash'] 是否存在 然后检查 auth['extra']['user_hash']['education'] 是否存在 然后检查 auth['extra']['user_hash']['education']['year']['name'] 等等..
我不认为使用异常处理是个好方法。
有什么好的方法吗?
谢谢
【问题讨论】:
标签: json ruby-on-rails-3 jagged-arrays