嵌套数组 ruby 类型错误:没有将哈希隐式转换为整数


def get_att(webinar_id)
finalArray = []
api_service = ApiService.new
response = api_service.get_attendees(webinar_id)
json = JSON.parse(response.body)
for x in json['_embedded']['attendeeParticipationResponses']
first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
email = json['_embedded']['attendeeParticipationResponses'][x]['email']
finalArray << [first_name, last_name, email]
end
# x = 2
# first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
# last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
# email = json['_embedded']['attendeeParticipationResponses'][x]['email']
# finalArray << [first_name, last_name, email]
Rails.logger.info(finalArray)
end

这个想法是返回一个数组数组,其中包含所有人及其 3 个标签。

我知道 JSON 解析数据正在工作,因为注释掉的代码工作得很好,我可以更改x赋值并运行。for 循环也可以工作,因为当我添加一个计数器时,它会json['_embedded']['attendeeParticipationResponses']计算 15 个响应。所以我知道有 15 个人在那里,我可以将它们一个接一个地添加到最终数组中(顺便说一下,我必须容纳多个数组(,但由于某种原因,我把它放在 for 循环中的第二个我得到了一个奇怪的错误,它完全读取:

TypeError: no implicit conversion of Hash into Integer from /Users/josh/Documents/GitHub/schools_health/lib/go_to_webinar/to_pipeline.rb:19:in `[]'

没关系,我修好了!这是一个语法问题。

我来自更多的Java背景,Ruby的循环语法使x成为一个对象。我以为它会包含数组索引。我通过将循环内的引用从:

first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']

自:

first_name = x['firstName']

最新更新