0

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.

8
  • If it's returning ["0"] as you claim, then adding [0] will work fine. Commented Jan 17, 2014 at 21:45
  • 1
    What should the result be? Commented Jan 17, 2014 at 21:48
  • @WayneConrad see what OP wrote I need it to give me just the integer. call["fields"]["count_1"][0] gives "0". But he wanted 0. Commented Jan 17, 2014 at 21:49
  • @Arup 0 is a reasonable interpretation of "just give me the integer." So is 48 (the ASCII code for the character "0"). Commented Jan 17, 2014 at 21:50
  • 2
    Based on all these problems you are happening, can you copy/paste the result of puts call.inspect? I think the data does not look like you have pasted, at this point. Commented Jan 17, 2014 at 21:59

3 Answers 3

2

Try as below using String#to_i

call["fields"]["count_1"][0].to_i # => 0
Sign up to request clarification or add additional context in comments.

4 Comments

I tried that. Didn't work. Very strange. Seems like it would.
@user2270029 what result you want.. 0 or "0" ?
I want the result of just the integer, so 0
@user2270029 It should work.. check your data, if it is exactly same as you have given here.
2

Some tips:

  1. 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'.

  2. Try 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. The last one should definitly be an Array.

  4. Add an if clause to check if call['fields'][['count_1'].is_empty?.

  5. Look for typos :)

1 Comment

It's strange because this same code is working on another page. I've literally copied and pasted it to check it.
0

For some reason the API call was making the zeros nil instead of zero. Thanks for all your help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.