0

I have JSON response.

result = {
  "owner":{
    "uid":"bb4123ac7950435eb516e2a47940b675",
    "firstName":"Tester",
    "lastName":"Test5577"
  }
}

I am trying to extract "uid" but getting the following error.

Ruby : TypeError: can't convert String into Integer

My code is:

@jdoc =JSON.parse(result)

@uid = @jdoc.fetch("owner").first.fetch("uid").to_i()   #Getting error here.

Would be very grateful for your support.

1
  • I have tried this on console and got the following result [29] pry(main)> @uid = @jdoc.fetch("owner").first.fetch("uid").to_i() TypeError: can't convert String into Integer from (pry):28:in fetch'` [30] pry(main)> @uid = @jdoc.fetch("owner").fetch("uid").to_i() => 0 [31] pry(main)> @uid = @jdoc.fetch("owner").fetch("uid") => "bb4123ac7950435eb516e2a47940b675" Commented May 29, 2015 at 12:00

4 Answers 4

1

A small change in your code should get the right data:

@jdoc = JSON.parse(result)
@uid = @json['owner']['uid'] #=> "bb4123ac7950435eb516e2a47940b675"

Also, you're trying to convert a string: "bb4123ac7950435eb516e2a47940b675" into integer: to_i() in your code. Which would be 0 as uid is a string of alphanumeric characters, and not a combination of some random numbers/integers. I would suggest that you save that information in a varchar column instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Surya. You are a star. It is working with @uid= @jdoc["owner"]["uid"]. Really appreciate your help.
0

Can you please print what's inside @jdoc after JSON.parse(result)

btw the uid contain string so you'll receive 0 as ouput with integer

"bb4123ac7950435eb516e2a47940b675".to_i => # 0
"111".to_i => # 111

Comments

0

you can access uid as follows:

@jdoc = JSON.parse(result)
@uid = @json['owner']['uid']
@uid = Integer(@uid) rescue 0

Comments

0

You can try this. I hope this will help you.

@uid = @jdoc.fetch("owner").first.fetch("uid").to_i()

## OUTPUT

# If you do it like this you will get follwing error
TypeError: can't convert String into Integer

But if you will do following you will get desire result.

@uid = @jdoc.fetch("owner").fetch("uid")

##OUTPUT

"bb4123ac7950435eb516e2a47940b675"

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.