Search code examples
arraysjsonruby-on-railsrubyapi

Can't access nested JSON Api data: no implicit conversion of String into Integer


Wondering if you could help. I am trying to access all the nested first_names from this API inside of elements: https://fantasy.premierleague.com/api/bootstrap-static/

Here's my controller code:

def index
    require 'net/http'
    require 'json'
    url = 'https://fantasy.premierleague.com/api/bootstrap-static/'
    uri = URI(url)
    response = Net::HTTP.get(uri)
    object = JSON.parse(response)
    @testy = object["elements"]["first_name"]
  end 

I am able to access all the data inside of elements just fine, but when I add ["first_name"], I get the error: no implicit conversion of String into Integer

Seems a bit weird? Surely it should just pull in whatever is inside of "first_name", whether it's an integer, string etc?

Thanks


Solution

  • It's not the least bit strange.

    object["elements"] is an array and when you call the [] method on a array the argument is coerced into an integer as its used to access array elements by index:

    irb(main):052:0> []["foo"]
    (irb):52:in `[]': no implicit conversion of String into Integer (TypeError)
    

    Surely it should just pull in whatever is inside of "first_name", whether it's an integer, string etc?

    In other languages like JavaScript you would just get null instead because what you expect to be a single object is actually an array.

    Do yourself a big favor and move the HTTP call and JSON processing out of the controller and into a separate component that you can test in isolation. It will make it a lot easier to spot simple issues like this.