parsing facebook json in rails avoid error occurred while evaluating nil.[]
I am trying to parse a json returned from facebook. Now my idea is to get as much as detailks as possible from the facebook json. So I use like ( assume auth is parse json from facebook)
education_array = auth['extra']['user_hash']['education']
education_array.each do |edu|
puts edu['school']['name']
puts edu['type']
puts edu['year']['name']
end
Now the problem here is that some people might have added the school name but not the year. so obviously
edu['year']['name'] will throw error telling "error occurred while evaluating nil.[]" .
How do I avoid this ?
one way which I thought was puts edu['year']['name']||""
but this would still throw error in case 'year' itself doesn't exist . (it would avoid error in case 'name' isn't found )
I don't want the following solution : check if auth['extra'] 开发者_运维问答exists then check if auth['extra']['user_hash'] exists then check if auth['extra']['user_hash']['education'] exists then check if auth['extra']['user_hash']['education']['year']['name'] and so on..
I don't think using exception handling is a good way.
Any good way ?
Thank you
Use the &&
operator to check for nils.
education_array.each do |edu|
puts edu['school'] && edu['school']['name']
puts edu['type']
puts edu['year'] && edu['year']['name']
end
By way of example:
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
精彩评论