英文:
Can't access nested JSON Api data: no implicit conversion of String into Integer
问题
我在尝试访问API中elements
里嵌套的所有first_names
,不过当我添加["first_name"]
时,出现了错误:no implicit conversion of String into Integer。这看起来有点奇怪,它应该可以获取到first_name
里的任何内容,无论是整数、字符串等。谢谢。
英文:
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
答案1
得分: 0
object["elements"]
是一个数组,当你在数组上调用 []
方法时,参数会被强制转换为整数,因为它用于通过索引访问数组元素:
object["elements"]
是一个数组,当你在数组上调用 []
方法时,参数会被强制转换为整数,因为它用于通过索引访问数组元素:
irb(main):052:0> []["foo"]
(irb):52:in `[]': no implicit conversion of String into Integer (TypeError)
在其他语言中,比如 JavaScript,你会得到一个 null,因为你期望的单一对象实际上是一个数组。
在这种情况下,最好将HTTP调用和JSON处理从控制器中移出,放到一个单独的组件中进行测试。这将使诸如这样的简单问题更容易发现。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论