I am making an api call and receiving the following response (it's long, so I'm showing the important part):
... "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:
undefined method `[]' for nil:NilClass
But it's not working.
使用String#to_i
尝试以下操作
call["fields"]["count_1"][0].to_i # => 0
Some tips:
Try wrapping the API response in JSON.parse(...)
. That is, if you're not making the call via a gem that already does this. This might require 'json'
.
Try call['fields']['count_1'].first.to_i
Do some debugging: check the value of call.class
, call['fields'].class
and call['fields']['count_1'].class
. The last one should definitly be an Array .
Add an if
clause to check if call['fields'][['count_1'].is_empty?
.
Look for typos :)
For some reason the API call was making the zeros nil instead of zero. Thanks for all your help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.