0

我正在尝试解析从 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

现在这里的问题是有些人可能添加了学校名称但没有添加年份。很明显

edu['year']['name'] 将抛出错误,告诉“在评估 nil.[] 时发生错误”。

我该如何避免这种情况?

我认为的一种方法是 edu['year']['name']||""

但是如果 'year' 本身不存在,这仍然会引发错误。(如果找不到“名称”,它将避免错误)

我不想要以下解决方案:检查 auth['extra'] 是否存在然后检查 auth['extra']['user_hash'] 是否存在然后检查 auth['extra']['user_hash']['education '] 存在然后检查 auth['extra']['user_hash']['education']['year']['name'] 等等..

我不认为使用异常处理是一个好方法。

有什么好办法吗?

谢谢

4

1 回答 1

1

使用&&运算符检查 nil。

education_array.each do |edu|
  puts edu['school'] && edu['school']['name']
  puts edu['type']
  puts edu['year'] && edu['year']['name']
end

例如:

edu = { 'school' => { 'name' => 'value' } }
edu['school'] && edu['school']['name'] # => 'value'

edu = { 'school' => { } }
edu['school'] && edu['school']['name'] # => nil

edu = { 'school' => { } }
edu['school'] && edu['school']['name'] # => nil
于 2011-06-27T12:58:43.040 回答