【问题标题】:Ruby : TypeError: can't convert String into IntegerRuby:TypeError:无法将字符串转换为整数
【发布时间】:2015-05-29 11:31:13
【问题描述】:

我有 JSON 响应。

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

我正在尝试提取“uid”,但出现以下错误。

Ruby : TypeError: can't convert String into Integer

我的代码是:

@jdoc =JSON.parse(result)

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

非常感谢您的支持。

【问题讨论】:

  • 我在控制台上试过了,结果如下[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"
  • 谢谢阿米特这很好用@jdoc.fetch("owner").fetch("uid")。谢谢:-)

标签: ruby json parsing jruby


【解决方案1】:

代码中的一个小改动应该会得到正确的数据:

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

此外,您正在尝试在代码中将字符串:“bb4123ac7950435eb516e2a47940b675”转换为整数:to_i()。这将是 0,因为 uid 是一串字母数字字符,而不是一些随机数/整数的组合。我建议您将该信息保存在 varchar 列中。

【讨论】:

  • 谢谢苏利亚。你是明星。它与@uid= @jdoc["owner"]["uid"] 一起使用。非常感谢您的帮助。
【解决方案2】:

你能把@jdoc里面的内容打印在JSON.parse(result)之后

顺便说一句,uid 包含字符串,因此您将收到 0 作为整数输出

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

【讨论】:

    【解决方案3】:

    您可以按如下方式访问uid:

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

    【讨论】:

    • 谢谢。它与@uid=@jdoc["owner"]["uid"] 一起使用。非常感谢您的帮助。
    【解决方案4】:

    你可以试试这个。我希望这会对你有所帮助。

    @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
    

    但如果你愿意跟随你会得到想要的结果。

    @uid = @jdoc.fetch("owner").fetch("uid")
    
    ##OUTPUT
    
    "bb4123ac7950435eb516e2a47940b675"
    

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多