0

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}

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Can you use the dig method? Your data structure is highly inconsistent and it's difficult to use. I've upated the code to make it even more paranoid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.