Reputation: 167
I have a probem when I parse file like this all works
{"StumbleUpon":0,"Reddit":0,"Facebook":{"total_count":19227,"comment_count":0,"share_count":19227},"LinkedIn":27}
my code:
module SocialShares
class Sharedcount < Base
def shares!
response = RestClient.get(url)
JSON.parse(response)['Facebook']["share_count"] || 0
end
private
def url
"https://free.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.secrets.socialshared_api_key}"
end
end
end
And when I parse this i have error TypeError: no implicit conversion of String into Integer
file: {"StumbleUpon":0,"Reddit":0,"Facebook":0,"LinkedIn":0}
Upvotes: 0
Views: 64
Reputation: 211540
That second structure doesn't have the necessary structure to navigate it that way. You need to approach this more cautiously:
def shares!
response = RestClient.get(url)
data = JSON.parse(response)
data['Facebook'].is_a?(Hash) && data['Facebook']["share_count"] || 0
end
You can also do this in Ruby 2.4 or later:
data.dig('Facebook', 'share_count').to_i
Upvotes: 1