简体   繁体   English

无法访问Ruby数组和哈希值

[英]Trouble Accessing Ruby Array and Hash Value

I am making an api call and receiving the following response (it's long, so I'm showing the important part): 我正在进行api调用并收到以下响应(很长,因此我在展示重要部分):

... "fields":{"count"_1:["0"],"count_2":["5"]} ...

when I do: 当我做:

call["fields"]["count_1"]

It returns 它返回

["0"]

I need it to give me just the integer. 我需要它来给我整数。 I tried: 我试过了:

call["fields"]["count_1"][0]

And I also tried: 我也尝试过:

call["fields"]["count_1"][0].to_i

I'm running this in Rails and it gives me the error: 我在Rails中运行它,它给了我错误:

undefined method `[]' for nil:NilClass

But it's not working. 但这不起作用。

使用String#to_i尝试以下操作

call["fields"]["count_1"][0].to_i # => 0

Some tips: 一些技巧:

  1. Try wrapping the API response in JSON.parse(...) . 尝试将API响应包装在JSON.parse(...) That is, if you're not making the call via a gem that already does this. 也就是说,如果您不通过已经执行此操作的gem进行呼叫。 This might require 'json' . 这可能require 'json'

  2. Try call['fields']['count_1'].first.to_i 尝试call['fields']['count_1'].first.to_i

  3. Do some debugging: check the value of call.class , call['fields'].class and call['fields']['count_1'].class . 进行一些调试:检查call.classcall['fields'].classcall['fields']['count_1'].class The last one should definitly be an Array . 最后一个绝对应该是Array

  4. Add an if clause to check if call['fields'][['count_1'].is_empty? 添加if子句以检查call['fields'][['count_1'].is_empty? .

  5. Look for typos :) 寻找错别字:)

For some reason the API call was making the zeros nil instead of zero. 由于某种原因,API调用将零设为零而不是零。 Thanks for all your help. 感谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM