Search code examples
rubyjsonparsingjruby

Ruby : TypeError: can't convert String into Integer


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.


Solution

  • 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.