无法访问嵌套的JSON API数据:将字符串隐式转换为整数。

huangapple go评论45阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月8日 23:02:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定