I'm working with the LinkedIn API to get companies' details. They are sending an XML response, so I simply converted the XML to a hash using the .to_hash
method
This is a sample hash I'm getting: http://pastebin.com/1bXtHZ2F
in some companies they have more than one locations and contact information, i want to parse this data and get the details like phone number, city, postal_code etc.
The structure of the response is not consistent. Sometimes location field itself is missing or the postal_code
is available only at the fourth location.
I tried two ways:
1.
def phone(locations)
(locations && locations["values"][0]["contactInfo"]["phone1"]) || nil
end
This is not working if the phone number is not available in the first array
2.
def phone(locations)
if locations["locations"]["total"].to_i == 1
locations["locations"]["location"]["contact_info"]["phone1"]
else
locations["locations"]["location"].each do |p|
if (!p["contact_info"]["phone1"].nil? || !p['contact_info'].nil?)
return p["contact_info"]["phone1"]
break
end
end
end
end
This is not working if the "location"
hash itself is missing from the response. I need a solution where I can search with the keys "city"
, "phone"
and "postal_code"
and update if it is present. If it returns an array, parse the array and get the non-empty data.
I've also read this StackOverflow answer.